﻿using HslCommunication.ModBus;
using HslCommunication;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Diagnostics;
using System.Net.NetworkInformation;
using HslCommunication.Enthernet;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace MES
{
    public partial class Form1 : Form
    {
        AutoSizeFormClass MyControlAutosize = new AutoSizeFormClass();
        //设备
        Device device1;
        Device device2;
        Device device3;
        Device device4;
        Device device5;
        Device device6;
        Device device7;
        Device device8;
        Device device9;

        //扫码枪
        ScanDevice scanDevice1_1;  //上板机1
        ScanDevice scanDevice1_2; //上板机2
        ScanDevice scanDevice6_1;  //ICT进板
        ScanDevice scanDevice6_2; //ICT出板+FCT进板

        //Task
        public Task DeviceTask1;
        public Task DeviceTask2;
        public Task DeviceTask3;
        public Task DeviceTask4;
        public Task DeviceTask5;
        public Task DeviceTask6;
        public Task DeviceTask7;
        public Task DeviceTask8;
        public Task DeviceTask9;

        public Task ICT_ReadTask;//循环读取ICT设备测试文件
        public Task FCT_ReadTask1;//循环读取FCT设备A轨测试文件
        public Task FCT_ReadTask2;//循环读取FCT设备B轨测试文件

        public Task SBJPortReportTask;//上板机Port报告
        public Task ICTScanTask;
        public Task FCTScanTask;
        Form2 form2 = new Form2();
        public bool AutoMode = false;


        //主界面控件列表和设备列表对应
        #region 显示状态
        public static List<Device> deviceList = new List<Device>();
        public static List<TextBox> TextBox_Scan = new List<TextBox>();
        public static List<Button> Button_DeviceState = new List<Button>();
        public static List<Button> Button_PLCConnect = new List<Button>();
        public static List<Button> Button_TCPConnect = new List<Button>();
        public static List<RichTextBox> RichTextBox_WarningBox = new List<RichTextBox>();
        public static List<DataGridView> DataGridView_SendList = new List<DataGridView>();
        public static List<DataGridView> DataGridView_ReciveList = new List<DataGridView>();
        #endregion

        #region 显示参数
        public static List<Label> Label_ID = new List<Label>();
        public static List<TextBox> TextBox_ID = new List<TextBox>();
        public static List<TextBox> TextBox_PLCIP = new List<TextBox>();
        public static List<TextBox> TextBox_PLCPort = new List<TextBox>();
        public static List<TextBox> TextBox_TCPIP = new List<TextBox>();
        public static List<TextBox> TextBox_TCPPort = new List<TextBox>();
        public static List<TextBox> TextBox_T1 = new List<TextBox>();
        public static List<TextBox> TextBox_T3 = new List<TextBox>();
        public static List<TextBox> TextBox_IdleDelayTime = new List<TextBox>();
        public static List<TextBox> TextBox_EAP_ALIVE_CHECK_Time = new List<TextBox>();
        public static List<Button> Button_PLCReconnect = new List<Button>();
        public static List<Button> Button_TCPReconnect = new List<Button>();
        #endregion

        public Form1()
        {
            InitializeComponent();
            MyControlAutosize.controllInitializeSize(this);
            Tool.form1 = this;
        }

        #region 方法//////////////方法//////////////方法//////////////方法//////////////方法//////////////方法//////////////方法//////////////方法//////////////方法//////////////

        private void ICTReaderTask()
        {
            DirectoryInfo theFolder = new DirectoryInfo(@"\\192.168.216.30\TestData");
            //相对共享文件夹的路径
            string fielpath = @"\#.dcl";
            //获取保存文件的路径
            string filename = theFolder.ToString() + fielpath;
            if (!Directory.Exists("D:\\ICT-TestData"))
            {
                Directory.CreateDirectory("D:\\ICT-TestData");
            }
            while (true)
            {

                if (File.Exists(filename))
                {
                    try
                    {
                        Tool.ICT_StopTime = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));
                        string info = File.ReadAllText(filename);
                        int processTime;
                        if (Tool.ICT_StopTime - Tool.ICT_StarTime > Int32.MaxValue)
                        {
                            processTime = 0;
                        }
                        else
                        {
                            processTime = Convert.ToInt32(Tool.ICT_StopTime - Tool.ICT_StarTime);
                        }
                        int fixtureTime = Convert.ToInt32(Tool.ICT_FixetureTime.ElapsedMilliseconds / 1000);
                        EDC_REPORT ICT_EDC_REPORT = Tool.CheckEDCReport_ICT(info, scanDevice6_1.ScanMSG, processTime, fixtureTime, out List<string> testData,out device6.Sorting);
                        if (ICT_EDC_REPORT.result == true)//表解析成功
                        {
                            Tool.ICT_EDC_REPORT = ICT_EDC_REPORT;
                            if (device6.TCPConnect)
                            {
                                byte[] data = SendEvent.ICT_JOB_SEND_REPORT(device6, testData, ICT_EDC_REPORT.PCBBarcode, ICT_EDC_REPORT.Pass.ToString(), out string Msg, out string transactionID);
                                DeviceSendMsg(device6, data, Msg);
                                device6.AddSendMsgList(transactionID);

                                data = SendEvent.EDC_REPORT(device6, ICT_EDC_REPORT, processTime.ToString(), Tool.ICT_StarTime.ToString(), Tool.ICT_StopTime.ToString(), out Msg, out transactionID);
                                DeviceSendMsg(device6, data, Msg);
                                device6.AddSendMsgList(transactionID);
                            }

                        }
                        Tool.ICT_StopTime = 0;
                        Tool.ICT_StarTime = 0;
                        Tool.ICT_EDC_REPORT.Pass = 1;
                    }
                    catch
                    {

                    }
                    try
                    {
                        if (!Directory.Exists("D:\\ICT-TestData\\" + DateTime.Now.ToString("yyyyMMdd")))
                        {
                            Directory.CreateDirectory("D:\\ICT-TestData\\" + DateTime.Now.ToString("yyyyMMdd"));
                        }
                        File.Move(filename, "D:\\ICT-TestData\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss-") + new Random().Next(1000, 9999) + ".txt");
                    }
                    catch
                    {

                    }
                }

                Ping ping = new Ping();
                PingReply pingReply = ping.Send("192.168.216.30");
                string m = pingReply.Status.ToString();
                if (m != "Success")
                {
                    bool status = false;

                    //连接共享文件夹
                    status = ConnectState(@"\\DESKTOP-C8SQGMO\TestData", "192.168.216.30", "");
                }
                Thread.Sleep(1000);
            }
        }
        private void FCTReaderTask1()
        {
            DirectoryInfo theFolder = new DirectoryInfo(@"\\192.168.216.40\TestData");
            //相对共享文件夹的路径
            string fielpath = @"\\192.168.216.40\TestData";
            //获取保存文件的路径
            string filename = theFolder.ToString() + fielpath;
            if (!Directory.Exists("D:\\FCT-TestData"))
            {
                Directory.CreateDirectory("D:\\FCT-TestData");
            }
            string[] fileList;
            while (true)
            {
                fileList = Directory.GetFiles(fielpath);
                if (fileList.Length > 0)
                {
                    try
                    {
                        string info = File.ReadAllText(fileList[0]);
                        Tool.FCT_StopTime1 = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));

                        int processTime;
                        if (Tool.FCT_StopTime1 - Tool.FCT_StarTime1 > Int32.MaxValue)
                        {
                            processTime = 0;
                        }
                        else
                        {
                            processTime = Convert.ToInt32(Tool.FCT_StopTime1 - Tool.FCT_StarTime1);
                        }
                        int waiteTime;
                        if (Tool.FCT_PartInTime1 - Tool.FCT_StarTime1 > Int32.MaxValue)
                        {
                            waiteTime = 0;
                        }
                        else
                        {
                            waiteTime = Convert.ToInt32(Tool.FCT_StopTime1 - Tool.FCT_StarTime1);
                            if (waiteTime <= 3)
                            {
                                waiteTime = 0;
                            }
                        }
                        int fixtureTime = Convert.ToInt32(Tool.FCT_FixetureTime1.ElapsedMilliseconds / 1000);

                        EDC_REPORT FCT_EDC_REPORT = Tool.CheckEDCReport_FCT(info, Tool.FCT_ID1, processTime, fixtureTime, waiteTime, out List<string> testData,out device7.Sorting);
                        if (FCT_EDC_REPORT.result == true)//表解析成功
                        {
                            Tool.FCT_EDC_REPORT = FCT_EDC_REPORT;
                            if (device7.TCPConnect)
                            {
                                byte[] data = SendEvent.FCT_JOB_SEND_REPORT(device7, FCT_EDC_REPORT, testData, out string Msg, out string transactionID);
                                DeviceSendMsg(device7, data, Msg);
                                device7.AddSendMsgList(transactionID);

                                data = SendEvent.EDC_REPORT(device7, FCT_EDC_REPORT, processTime.ToString(), Tool.FCT_StarTime1.ToString(), Tool.FCT_StopTime1.ToString(), out Msg, out transactionID);
                                DeviceSendMsg(device7, data, Msg);
                                device7.AddSendMsgList(transactionID);
                            }

                        }


                        Tool.FCT_StopTime1 = 0;
                        Tool.FCT_StarTime1 = 0;
                        Tool.FCT_PartInTime1 = 0;
                        Tool.FCT_ID1 = "";
                        Tool.FCT_FixetureTime1.Reset();
                        Tool.FCT_EDC_REPORT.Pass = 1;

                    }
                    catch
                    {

                    }


                    try
                    {
                        if (!Directory.Exists("D:\\FCT-TestData-A轨道\\" + DateTime.Now.ToString("yyyyMMdd")))
                        {
                            Directory.CreateDirectory("D:\\FCT-TestData-A轨道\\" + DateTime.Now.ToString("yyyyMMdd"));
                        }
                        File.Move(fileList[0], "D:\\FCT-TestData-A轨道\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss-") + new Random().Next(1000, 9999) + ".txt");
                    }
                    catch
                    {

                    }
                }

                Ping ping = new Ping();
                PingReply pingReply = ping.Send("192.168.216.40");
                string m = pingReply.Status.ToString();
                if (m != "Success")
                {
                    bool status = false;

                    //连接共享文件夹
                    status = ConnectState(@"\\DESKTOP-C8SQGMO\TestData", "192.168.216.40", "");
                }
                Thread.Sleep(1000);
            }
        }//A轨测试
        private void FCTReaderTask2()
        {
            DirectoryInfo theFolder = new DirectoryInfo(@"\\192.168.216.41\TestData");
            //相对共享文件夹的路径
            string fielpath = @"\\192.168.216.41\TestData";
            //获取保存文件的路径
            string filename = theFolder.ToString() + fielpath;
            if (!Directory.Exists("D:\\FCT-TestData"))
            {
                Directory.CreateDirectory("D:\\FCT-TestData");
            }
            string[] fileList;
            while (true)
            {
                fileList = Directory.GetFiles(fielpath);
                if (fileList.Length > 0)
                {
                    try
                    {
                        string info = File.ReadAllText(fileList[0]);
                        Tool.FCT_StopTime2 = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));

                        int processTime;
                        if (Tool.FCT_StopTime2 - Tool.FCT_StarTime2 > Int32.MaxValue)
                        {
                            processTime = 0;
                        }
                        else
                        {
                            processTime = Convert.ToInt32(Tool.FCT_StopTime2 - Tool.FCT_StarTime2);
                        }
                        int waiteTime;
                        if (Tool.FCT_PartInTime2 - Tool.FCT_StarTime2 > Int32.MaxValue)
                        {
                            waiteTime = 0;
                        }
                        else
                        {
                            waiteTime = Convert.ToInt32(Tool.FCT_StopTime2 - Tool.FCT_StarTime2);
                            if (waiteTime <= 3)
                            {
                                waiteTime = 0;
                            }
                        }

                        int fixtureTime = Convert.ToInt32(Tool.FCT_FixetureTime2.ElapsedMilliseconds / 1000);

                        EDC_REPORT FCT_EDC_REPORT = Tool.CheckEDCReport_FCT(info, Tool.FCT_ID2, processTime, fixtureTime, waiteTime, out List<string> testData, out device7.Sorting);
                        if (FCT_EDC_REPORT.result == true)//表解析成功
                        {
                            Tool.FCT_EDC_REPORT = FCT_EDC_REPORT;
                            if (device7.TCPConnect)
                            {
                                byte[] data = SendEvent.FCT_JOB_SEND_REPORT(device7, FCT_EDC_REPORT, testData, out string Msg, out string transactionID);
                                DeviceSendMsg(device7, data, Msg);
                                device7.AddSendMsgList(transactionID);

                                data = SendEvent.EDC_REPORT(device7, FCT_EDC_REPORT, processTime.ToString(), Tool.FCT_StarTime2.ToString(), Tool.FCT_StopTime2.ToString(), out Msg, out transactionID);
                                DeviceSendMsg(device7, data, Msg);
                                device7.AddSendMsgList(transactionID);
                            }

                        }


                        Tool.FCT_StopTime2 = 0;
                        Tool.FCT_PartInTime2 = 0;
                        Tool.FCT_StarTime2 = 0;
                        Tool.FCT_ID2 = "";
                        Tool.FCT_FixetureTime2.Reset();
                        Tool.FCT_EDC_REPORT.Pass = 1;

                    }
                    catch
                    {

                    }


                    try
                    {
                        if (!Directory.Exists("D:\\FCT-TestData-B轨道\\" + DateTime.Now.ToString("yyyyMMdd")))
                        {
                            Directory.CreateDirectory("D:\\FCT-TestData-B轨道\\" + DateTime.Now.ToString("yyyyMMdd"));
                        }
                        File.Move(fileList[0], "D:\\FCT-TestData-B轨道\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss-") + new Random().Next(1000, 9999) + ".txt");
                    }
                    catch
                    {

                    }
                }

                Ping ping = new Ping();
                PingReply pingReply = ping.Send("192.168.216.40");
                string m = pingReply.Status.ToString();
                if (m != "Success")
                {
                    bool status = false;

                    //连接共享文件夹
                    status = ConnectState(@"\\DESKTOP-C8SQGMO\TestData", "192.168.216.40", "");
                }
                Thread.Sleep(1000);
            }
        }//B轨测试
        /// <summary>
        /// 连接局域网PC，ICT,FCT读取测试文件用
        /// </summary>
        /// <param name="path">远程文件路径</param>
        /// <param name="userName">远程电脑用户名</param>
        /// <param name="passWord">远程电脑密码</param>
        /// <returns></returns>
        public bool ConnectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
                AddMSG(richTextBox1, userName + "连接成功");
            }
            catch (Exception ex)
            {
                AddMSG(richTextBox1, userName + "连接失败");

            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }
        /// <summary>
        /// 判断报警列表,ICT,FCT用
        /// </summary>
        /// <param name="list"></param>
        /// <param name="k"></param>
        private void CheckErrorList(ref List<int> list, ref int k, int mode)
        {
            //mode=1,D20,  mode=2,D21
            int res = -1;
            double test = Math.Log(k, 2);

            res = (int)(Math.Log(k, 2));
            if (mode == 1)
            {
                list.Add(res);
            }
            else if (mode == 2)
            {
                list.Add(res + 16);//报警列表D20有16个
            }
            k -= Convert.ToInt32(Math.Pow(2, res));
            if (k == 0)
                return;
            else
            {
                CheckErrorList(ref list, ref k, mode);
            }

        }
        /// <summary>
        /// 确认同一事件是否在T3时间内重复发送
        /// </summary>
        /// <param name="EventName">事件名称</param>
        /// <param name="device">设备</param>
        /// <returns></returns>
        public bool CheckT3(string EventName, Device device)
        {
            lock (this)
            {
                if (device.SendEventList.Contains(EventName))
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 在RichTextBox添加文本
        /// </summary>
        /// <param name="richTextBox"></param>
        /// <param name="MSG"></param>
        public void AddMSG(RichTextBox richTextBox, string MSG)
        {
            this.BeginInvoke(new Action(() =>
            {
                richTextBox.AppendText(DateTime.Now.ToString("yyyy/MM/dd-HH:mm:ss") + ": " + MSG + "\r");
                richTextBox.HideSelection = false;
                if (richTextBox.TextLength > 5000)
                {
                    richTextBox.Clear();
                }
            }));
        }
        public void AddMSG(Device device, string MSG)
        {
            int index = deviceList.IndexOf(device);
            this.BeginInvoke(new Action(() =>
            {
                RichTextBox_WarningBox[index].AppendText(DateTime.Now.ToString("yyyy/MM/dd-HH:mm:ss") + ": " + MSG + "\r");
                RichTextBox_WarningBox[index].HideSelection = false;
                if (RichTextBox_WarningBox[index].TextLength > 5000)
                {
                    RichTextBox_WarningBox[index].Clear();
                }
            }));
        }
        /// <summary>
        /// 在dataGrid列表添加文本
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <param name="Info"></param>
        /// <param name="mode"></param>
        public void AddInfoOnDataGridView(DataGridView dataGridView, string Info, string mode)
        {
            //mode=1 Send，mode=2 Recive
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(Info);
                XmlNode root = xmlDocument.DocumentElement;
                string messageName = root.SelectSingleNode("Header/MESSAGENAME").InnerText;
                string transactionID = root.SelectSingleNode("Header/TRANSACTIONID").InnerText;
                string body = root.SelectSingleNode("Body").InnerXml;

                this.BeginInvoke((Action)(() =>
                {
                    DataGridViewRow dataGridViewRow = new DataGridViewRow();
                    dataGridViewRow.CreateCells(dataGridView);

                    dataGridViewRow.Cells[0].Value = DateTime.Now.ToString("yyyy/MM/dd-HH:mm:ss");
                    dataGridViewRow.Cells[1].Value = mode;
                    dataGridViewRow.Cells[2].Value = messageName;
                    dataGridViewRow.Cells[3].Value = transactionID;
                    dataGridViewRow.Cells[4].Value = body;
                    dataGridView.Rows.Insert(0, dataGridViewRow);

                    if (dataGridView.Rows.Count > 51)
                    {
                        dataGridView.Rows.RemoveAt(dataGridView.Rows.Count - 2);
                    }

                }));

            }
            catch
            {

            }

        }

        /// <summary>
        /// 在dataGrid列表添加文本，CIM信息专用
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <param name="Info"></param>
        /// <param name="mode"></param>
        public void AddCIMInfoOnDataGridView(DataGridView dataGridView, string Info)
        {
            //mode=1 Send，mode=2 Recive
            try
            {
                this.BeginInvoke((Action)(() =>
                {
                    DataGridViewRow dataGridViewRow = new DataGridViewRow();
                    dataGridViewRow.CreateCells(dataGridView);
                    dataGridViewRow.Cells[0].Value = DateTime.Now.ToString("yyyy/MM/dd-HH:mm:ss.ff");
                    dataGridViewRow.Cells[1].Value = Info;
                    dataGridView.Rows.Insert(0, dataGridViewRow);
                    if (dataGridView.Rows.Count > 51)
                    {
                        dataGridView.Rows.RemoveAt(dataGridView.Rows.Count - 2);
                    }

                }));
            }
            catch
            {

            }

        }


        /// <summary>
        /// 设备向Mes发送数据+本地显示+Log储存
        /// </summary>
        /// <param name="device"></param>
        /// <param name="Info"></param>
        /// <param name="msg"></param>
        public void DeviceSendMsg(Device device, byte[] Info, string msg)
        {
            int index = deviceList.IndexOf(device);
            device.TCPClient.ClientSendMSG(Info);
            Tool.SaveLog(device, LogMod.Mes交互记录.ToString(), "[Send]" + "\r\n" + msg);
            AddInfoOnDataGridView(DataGridView_SendList[index], msg, "Send");

        }
        /// <summary>
        /// 根据通讯是否连接来改变界面显示
        /// </summary>
        /// <param name="device"></param>
        /// <param name="PLC_CommState"></param>
        /// <param name="TCP_CommState"></param>
        public void ChangeCommShow(Device device, bool PLC_CommState, bool TCP_CommState)
        {
            int index = deviceList.IndexOf(device);

            if (PLC_CommState)
            {
                this.BeginInvoke(new Action(() =>
                {
                    Button_PLCConnect[index].BackColor = Color.Green;
                    Button_PLCConnect[index].Text = "PLC已连接";
                }));
            }
            else
            {
                this.BeginInvoke(new Action(() =>
                {
                    Button_PLCConnect[index].BackColor = Color.Red;
                    Button_PLCConnect[index].Text = "PLC未连接";
                }));
            }

            if (TCP_CommState)
            {
                this.BeginInvoke(new Action(() =>
                {
                    Button_TCPConnect[index].BackColor = Color.Green;
                    Button_TCPConnect[index].Text = "Mes已连接";
                }));
            }
            else
            {
                this.BeginInvoke(new Action(() =>
                {
                    Button_TCPConnect[index].BackColor = Color.Red;
                    Button_TCPConnect[index].Text = "Mes未连接";
                }));
            }



        }
        /// <summary>
        /// Button_Click事件，绑定界面参数到设备参数
        /// </summary>
        private void BoundConfig(int index)
        {
            index -= 1;
            try
            {
                Label_ID[index].Text = TextBox_ID[index].Text;
                deviceList[index].DeviceID = TextBox_ID[index].Text;
                deviceList[index].PLC_IP = TextBox_PLCIP[index].Text;
                deviceList[index].PLC_Port = Convert.ToInt32(TextBox_PLCPort[index].Text);
                deviceList[index].TCP_IP = TextBox_TCPIP[index].Text;
                deviceList[index].TCP_Port = Convert.ToInt32(TextBox_TCPPort[index].Text);
                deviceList[index].DelayTime_T1 = Convert.ToInt32(TextBox_T1[index].Text);
                deviceList[index].DelayTime_T3 = Convert.ToInt32(TextBox_T3[index].Text);
                deviceList[index].Idle_Delay_Time = Convert.ToInt32(TextBox_IdleDelayTime[index].Text);
                deviceList[index].TCPAliveCheckTime = Convert.ToInt32(TextBox_EAP_ALIVE_CHECK_Time[index].Text);
                deviceList[index].WriteConfig();
            }
            catch
            {
                MessageBox.Show("输入的参数有误");
            }
        }
        /// <summary>
        /// 手动改变设备连接状态，PLC&Socket
        /// </summary>
        /// <param name="device"></param>
        private void ChangeButtonState(int index, string buttonName)
        {
            index -= 1;

            //PLC重连按钮
            if (buttonName == "PLC_Reconnect")
            {
                if (deviceList[index].PLCReConnect)
                {
                    deviceList[index].PLCReConnect = false;
                    Button_PLCReconnect[index].Text = "PLC自动重连未启用";
                    Button_PLCReconnect[index].BackColor = Color.Red;
                }
                else
                {
                    deviceList[index].PLCReConnect = true;
                    Button_PLCReconnect[index].Text = "PLC自动重连启用";
                    Button_PLCReconnect[index].BackColor = Color.Green;
                }
                deviceList[index].WriteConfig();
            }

            //TCP重连按钮
            if (buttonName == "TCP_Reconnect")
            {
                if (deviceList[index].TCPReConnect)
                {
                    deviceList[index].TCPReConnect = false;
                    Button_TCPReconnect[index].Text = "Mes自动重连未启用";
                    Button_TCPReconnect[index].BackColor = Color.Red;
                }
                else
                {
                    deviceList[index].TCPReConnect = true;
                    Button_TCPReconnect[index].Text = "Mes自动重连启用";
                    Button_TCPReconnect[index].BackColor = Color.Green;
                }
                deviceList[index].WriteConfig();
            }

            //PLC连接手动开关
            if (buttonName == "PLC_Connect")
            {
                if (deviceList[index].PLCConnect)
                {
                    deviceList[index].CloseModBus();
                    deviceList[index].PLCConnect = false;
                }
                else
                {
                    deviceList[index].ConnectPLC();
                }
                ChangeCommShow(deviceList[index], deviceList[index].PLCConnect, deviceList[index].TCPConnect);
            }

            //Socket连接手动开关
            if (buttonName == "TCP_Connect")
            {
                if (deviceList[index].TCPConnect)
                {
                    int res = deviceList[index].CloseSocket();
                    if (res == 0)
                    {
                        deviceList[index].TCPConnect = false;
                    }
                }
                else
                {
                    deviceList[index].ConnectSocket();
                }
                ChangeCommShow(deviceList[index], deviceList[index].PLCConnect, deviceList[index].TCPConnect);
            }


        }
        private void ChangeButtonState(string buttonName)
        {
            if (buttonName == "Button_Scan_1_1")
            {
                if (scanDevice1_1.TCPConnect == true)
                {
                    int res = scanDevice1_1.CloseSocket();
                    if (res == 0)
                    {
                        Button_Scan_1_1.BackColor = Color.Red;
                    }
                }
                else if (scanDevice1_1.TCPConnect == false)
                {
                    int res = scanDevice1_1.ConnectSocket();
                    if (res == 0)
                    {
                        Button_Scan_1_1.BackColor = Color.Green;
                    }
                }
            }

            if (buttonName == "Button_Scan_1_2")
            {
                if (scanDevice1_2.TCPConnect == true)
                {
                    int res = scanDevice1_2.CloseSocket();
                    if (res == 0)
                    {
                        Button_Scan_1_2.BackColor = Color.Red;
                    }
                }
                else if (scanDevice1_2.TCPConnect == false)
                {
                    int res = scanDevice1_2.ConnectSocket();
                    if (res == 0)
                    {
                        Button_Scan_1_2.BackColor = Color.Green;
                    }
                }
            }

            if (buttonName == "Button_ScanUsing_1")
            {
                if (Tool.SBJ_ScanUsing == true)
                {
                    Tool.SBJ_ScanUsing = false;
                    Button_ScanUsing_1.Text = "扫码枪停用";
                    Button_ScanUsing_1.BackColor = Color.Red;
                    device1.PLC.WriteCoil("8302", true);
                    device1.PLC.WriteCoil("8303", true);
                }
                else if (Tool.SBJ_ScanUsing == false)
                {
                    Tool.SBJ_ScanUsing = true;
                    Button_ScanUsing_1.Text = "扫码枪启用";
                    Button_ScanUsing_1.BackColor = Color.Green;
                    device1.PLC.WriteCoil("8302", false);
                    device1.PLC.WriteCoil("8303", false);
                    MessageBox.Show("打开软件扫码枪启用后，上板机设备扫码功能必须开启！", "提示", MessageBoxButtons.OK);
                }
            }

            if (buttonName == "Button_ScanUsing_6")
            {
                if (Tool.ICT_ScanUsing == true)
                {
                    Tool.ICT_ScanUsing = false;
                    Button_ScanUsing_6.Text = "扫码枪停用";
                    Button_ScanUsing_6.BackColor = Color.Red;
                }
                else if (Tool.ICT_ScanUsing == false)
                {
                    Tool.ICT_ScanUsing = true;
                    Button_ScanUsing_6.Text = "扫码枪启用";
                    Button_ScanUsing_6.BackColor = Color.Green;
                }
            }

            if (buttonName == "Button_ScanUsing_7")
            {
                if (Tool.FCT_ScanUsing == true)
                {
                    Tool.FCT_ScanUsing = false;
                    Button_ScanUsing_7.Text = "扫码枪停用";
                    Button_ScanUsing_7.BackColor = Color.Red;
                }
                else if (Tool.FCT_ScanUsing == false)
                {
                    Tool.FCT_ScanUsing = true;
                    Button_ScanUsing_7.Text = "扫码枪启用";
                    Button_ScanUsing_7.BackColor = Color.Green;
                }
            }

            if (buttonName == "Button_Mode_1")
            {
                if (Tool.SBJmode == 1)
                {
                    Tool.SBJmode = 2;
                    Button_Mode_1.Text = "手动上板模式";
                    Button_Mode_1.BackColor = Color.Yellow;

                }
                else if (Tool.SBJmode == 2)
                {
                    Tool.SBJmode = 1;
                    Button_Mode_1.Text = "AGV上板模式";
                    Button_Mode_1.BackColor = Color.Green;
                }
            }

            if (buttonName == "Button_Scan_6_1")
            {
                if (scanDevice6_1.TCPConnect == true)
                {
                    int res = scanDevice6_1.CloseSocket();
                    if (res == 0)
                    {
                        Button_Scan_6_1.BackColor = Color.Red;
                    }
                }
                else if (scanDevice6_1.TCPConnect == false)
                {
                    int res = scanDevice6_1.ConnectSocket();
                    if (res == 0)
                    {
                        Button_Scan_6_1.BackColor = Color.Green;
                    }
                }
            }

            if (buttonName == "Button_Scan_6_2")
            {
                if (scanDevice6_2.TCPConnect == true)
                {
                    int res = scanDevice6_2.CloseSocket();
                    if (res == 0)
                    {
                        Button_Scan_6_2.BackColor = Color.Red;
                    }
                }
                else if (scanDevice6_2.TCPConnect == false)
                {
                    int res = scanDevice6_2.ConnectSocket();
                    if (res == 0)
                    {
                        Button_Scan_6_2.BackColor = Color.Green;
                    }
                }
            }
        }
        #endregion

        #region  打开软件////打开软件////打开软件////打开软件////打开软件////打开软件////打开软件////打开软件////打开软件////打开软件//打开软件////////打开软件////////打开软件////////打开软件////
        private void Form1_Load(object sender, EventArgs e)
        {
            device1 = new Device("上板机");
            device2 = new Device("上载具");
            device3 = new Device("下盖板&人工插件");
            device4 = new Device("暂存机");
            device5 = new Device("拆载具");
            device6 = new Device("ICT");
            device7 = new Device("FCT");
            device8 = new Device("翻板机");
            device9 = new Device("移栽&接驳");
            scanDevice1_1 = new ScanDevice("扫码枪1_1");
            scanDevice1_2 = new ScanDevice("扫码枪1_2");
            scanDevice6_1 = new ScanDevice("扫码枪6_1");
            scanDevice6_2 = new ScanDevice("扫码枪6_2");
            ReadConfig();
            AddControlList();

            #region 设备状态显示+各个线程开起
            for (int i = 0; i < deviceList.Count; i++)
            {
                ShowConfigOnForm(deviceList[i]);
            }
            TextBox_InputWaiteTime_1.Text = Tool.SBJ_inputWaiteTime.ToString();


            device1.SetMsgCallBackHandle(ReciveMsgCallBack1);
            device1.DeviceStar();
            DeviceTask1 = new Task(TaskRun1);
            DeviceTask1.Start();

            device2.SetMsgCallBackHandle(ReciveMsgCallBack2);
            device2.DeviceStar();
            DeviceTask2 = new Task(TaskRun2);
            DeviceTask2.Start();

            device3.SetMsgCallBackHandle(ReciveMsgCallBack3);
            device3.DeviceStar();
            DeviceTask3 = new Task(TaskRun3);
            DeviceTask3.Start();

            device4.SetMsgCallBackHandle(ReciveMsgCallBack4);
            device4.DeviceStar();
            DeviceTask4 = new Task(TaskRun4);
            DeviceTask4.Start();

            device5.SetMsgCallBackHandle(ReciveMsgCallBack5);
            device5.DeviceStar();
            DeviceTask5 = new Task(TaskRun5);
            DeviceTask5.Start();

            device6.SetMsgCallBackHandle(ReciveMsgCallBack6);
            device6.DeviceStar();
            DeviceTask6 = new Task(TaskRun6);
            DeviceTask6.Start();

            device7.SetMsgCallBackHandle(ReciveMsgCallBack7);
            device7.DeviceStar();
            DeviceTask7 = new Task(TaskRun7);
            DeviceTask7.Start();

            device8.SetMsgCallBackHandle(ReciveMsgCallBack8);
            device8.DeviceStar();
            DeviceTask8 = new Task(TaskRun8);
            DeviceTask8.Start();

            device9.SetMsgCallBackHandle(ReciveMsgCallBack9);
            device9.DeviceStar();
            DeviceTask9 = new Task(TaskRun9);
            DeviceTask9.Start();
            #endregion

            //连接扫码枪，，测试
            ScanDeviceInfoOnForm();
            ScanDeviceConnectServer();

            ////连接共享文件夹
            Task.Run(() =>
            {
                bool status = false;
                //连接共享文件夹
                status = ConnectState(@"\\DESKTOP-C8SQGMO\TestData", "192.168.216.30", "");
            });
            Task.Run(() =>
            {
                bool status = false;
                //连接共享文件夹
                status = ConnectState(@"\\DESKTOP-C8SQGMO\TestData", "192.168.216.40", "");
            });
            Task.Run(() =>
            {
                bool status = false;
                //连接共享文件夹
                status = ConnectState(@"\\DESKTOP-C8SQGMO\TestData", "192.168.216.41", "");
            });
            ICT_ReadTask = new Task(ICTReaderTask);
            ICT_ReadTask.Start();
            FCT_ReadTask1 = new Task(FCTReaderTask1);
            FCT_ReadTask1.Start();
            FCT_ReadTask2 = new Task(FCTReaderTask2);
            FCT_ReadTask2.Start();
            ICTScanTask = new Task(ICT_Task);
            ICTScanTask.Start();
            FCTScanTask = new Task(FCT_Task);
            FCTScanTask.Start();

        }
        private void Form1_Shown(object sender, EventArgs e)
        {
            timer1.Start();
            Tool.ReadConfig();
            if (Tool.SBJ_ScanUsing == false)
            {
                Button_ScanUsing_1.Text = "扫码枪停用";
                Button_ScanUsing_1.BackColor = Color.Red;
                Task.Run(() =>
                {
                    device1.PLC.WriteCoil("8302", true);
                    device1.PLC.WriteCoil("8303", true);
                });
            }
            else if (Tool.SBJ_ScanUsing == true)
            {
                Button_ScanUsing_1.Text = "扫码枪启用";
                Button_ScanUsing_1.BackColor = Color.Green;
            }
            if (Tool.SBJmode == 2)
            {
                Task.Run(new Action(() =>
                {
                    int time = 0;
                    while (true)
                    {
                        time += 100;
                        if (device1.TCPConnect)
                        {
                            foreach (var item in Tool.SBJPortState)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, item.Key, "0", "", out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                Thread.Sleep(100);
                            }
                            SBJPortReportTask = new Task(SBJPortReport);
                            SBJPortReportTask.Start(); //上板机独用
                            break;
                        }
                        if (time > 10000)
                        {
                            SBJPortReportTask = new Task(SBJPortReport);
                            SBJPortReportTask.Start(); //上板机独用
                            break;
                        }
                        Thread.Sleep(100);
                    }

                }));

            }

            if (Tool.ICT_ScanUsing == false)
            {
                Button_ScanUsing_6.Text = "扫码枪停用";
                Button_ScanUsing_6.BackColor = Color.Red;
            }
            else if (Tool.ICT_ScanUsing == true)
            {
                Button_ScanUsing_6.Text = "扫码枪启用";
                Button_ScanUsing_6.BackColor = Color.Green;
            }

            if (Tool.FCT_ScanUsing == false)
            {
                Button_ScanUsing_7.Text = "扫码枪停用";
                Button_ScanUsing_7.BackColor = Color.Red;
            }
            else if (Tool.FCT_ScanUsing == true)
            {
                Button_ScanUsing_7.Text = "扫码枪启用";
                Button_ScanUsing_7.BackColor = Color.Green;
            }

            AutoMode = true;
            Task Task_Swithc_mode = new Task(CIM_AutoMode);
            Task_Swithc_mode.Start();


        }
        private void CIM_AutoMode()
        {
            string msg = "";
            string ID = "";
            byte[] sendmsg;
            while (device1.TCPConnect==false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device1, "1", out msg, out ID);
            DeviceSendMsg(device1, sendmsg, msg);

            while (device2.TCPConnect == false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device2, "1", out msg, out ID);
            DeviceSendMsg(device2, sendmsg, msg);

            while (device3.TCPConnect == false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device3, "1", out msg, out ID);
            DeviceSendMsg(device3, sendmsg, msg);


            while (device4.TCPConnect == false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device4, "1", out msg, out ID);
            DeviceSendMsg(device4, sendmsg, msg);

            while (device5.TCPConnect == false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device5, "1", out msg, out ID);
            DeviceSendMsg(device5, sendmsg, msg);

            while (device6.TCPConnect == false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device6, "1", out msg, out ID);
            DeviceSendMsg(device6, sendmsg, msg);

            while (device7.TCPConnect == false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device7, "1", out msg, out ID);
            DeviceSendMsg(device7, sendmsg, msg);

            while (device8.TCPConnect == false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device8, "1", out msg, out ID);
            DeviceSendMsg(device8, sendmsg, msg);

            while (device9.TCPConnect == false)
            {
                Application.DoEvents();
            }
            sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device9, "1", out msg, out ID);
            DeviceSendMsg(device9, sendmsg, msg);


            Task task = Task.Run(Task_BlueLight);

        }
        public void ReadConfig()
        {
            device1.ReadConfig();
            device2.ReadConfig();
            device3.ReadConfig();
            device4.ReadConfig();
            device5.ReadConfig();
            device6.ReadConfig();
            device7.ReadConfig();
            device8.ReadConfig();
            device9.ReadConfig();

            scanDevice1_1.ReadConfig();
            scanDevice1_2.ReadConfig();
            scanDevice6_1.ReadConfig();
            scanDevice6_2.ReadConfig();

            Product.LoadLastPart();
        }
        private void AddControlList()
        {
            #region 添加设备_1控件
            deviceList.Add(device1);
            TextBox_Scan.Add(TextBox_Scan_1_1);
            Button_DeviceState.Add(Button_DeviceState_1);
            Button_TCPConnect.Add(Button_TCPConnect_1);
            Button_PLCConnect.Add(Button_PLCConnect_1);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_1);
            DataGridView_SendList.Add(DataGridView_SendList_1);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_1);

            Label_ID.Add(Label_ID_1);
            TextBox_ID.Add(TextBox_ID_1);
            TextBox_PLCIP.Add(TextBox_PLCIP_1);
            TextBox_PLCPort.Add(TextBox_PLCPort_1);
            TextBox_TCPIP.Add(TextBox_TCPIP_1);
            TextBox_TCPPort.Add(TextBox_TCPPort_1);
            TextBox_T1.Add(TextBox_T1_1);
            TextBox_T3.Add(TextBox_T3_1);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_1);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_1);
            Button_TCPReconnect.Add(Button_TCPReconnect_1);
            Button_PLCReconnect.Add(Button_PLCReconnect_1);
            #endregion

            #region 添加设备_2控件
            deviceList.Add(device2);
            TextBox_Scan.Add(TextBox_Scan_2);
            Button_DeviceState.Add(Button_DeviceState_2);
            Button_TCPConnect.Add(Button_TCPConnect_2);
            Button_PLCConnect.Add(Button_PLCConnect_2);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_2);
            DataGridView_SendList.Add(DataGridView_SendList_2);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_2);

            Label_ID.Add(Label_ID_2);
            TextBox_ID.Add(TextBox_ID_2);
            TextBox_PLCIP.Add(TextBox_PLCIP_2);
            TextBox_PLCPort.Add(TextBox_PLCPort_2);
            TextBox_TCPIP.Add(TextBox_TCPIP_2);
            TextBox_TCPPort.Add(TextBox_TCPPort_2);
            TextBox_T1.Add(TextBox_T1_2);
            TextBox_T3.Add(TextBox_T3_2);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_2);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_2);
            Button_TCPReconnect.Add(Button_TCPReconnect_2);
            Button_PLCReconnect.Add(Button_PLCReconnect_2);
            #endregion

            #region 添加设备_3控件
            deviceList.Add(device3);
            TextBox_Scan.Add(TextBox_Scan_3);
            Button_DeviceState.Add(Button_DeviceState_3);
            Button_TCPConnect.Add(Button_TCPConnect_3);
            Button_PLCConnect.Add(Button_PLCConnect_3);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_3);
            DataGridView_SendList.Add(DataGridView_SendList_3);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_3);

            Label_ID.Add(Label_ID_3);
            TextBox_ID.Add(TextBox_ID_3);
            TextBox_PLCIP.Add(TextBox_PLCIP_3);
            TextBox_PLCPort.Add(TextBox_PLCPort_3);
            TextBox_TCPIP.Add(TextBox_TCPIP_3);
            TextBox_TCPPort.Add(TextBox_TCPPort_3);
            TextBox_T1.Add(TextBox_T1_3);
            TextBox_T3.Add(TextBox_T3_3);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_3);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_3);
            Button_TCPReconnect.Add(Button_TCPReconnect_3);
            Button_PLCReconnect.Add(Button_PLCReconnect_3);
            #endregion

            #region 添加设备_4控件
            deviceList.Add(device4);
            TextBox_Scan.Add(TextBox_Scan_4);
            Button_DeviceState.Add(Button_DeviceState_4);
            Button_TCPConnect.Add(Button_TCPConnect_4);
            Button_PLCConnect.Add(Button_PLCConnect_4);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_4);
            DataGridView_SendList.Add(DataGridView_SendList_4);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_4);

            Label_ID.Add(Label_ID_4);
            TextBox_ID.Add(TextBox_ID_4);
            TextBox_PLCIP.Add(TextBox_PLCIP_4);
            TextBox_PLCPort.Add(TextBox_PLCPort_4);
            TextBox_TCPIP.Add(TextBox_TCPIP_4);
            TextBox_TCPPort.Add(TextBox_TCPPort_4);
            TextBox_T1.Add(TextBox_T1_4);
            TextBox_T3.Add(TextBox_T3_4);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_4);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_4);
            Button_TCPReconnect.Add(Button_TCPReconnect_4);
            Button_PLCReconnect.Add(Button_PLCReconnect_4);
            #endregion

            #region 添加设备_5控件
            deviceList.Add(device5);
            TextBox_Scan.Add(TextBox_Scan_5);
            Button_DeviceState.Add(Button_DeviceState_5);
            Button_TCPConnect.Add(Button_TCPConnect_5);
            Button_PLCConnect.Add(Button_PLCConnect_5);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_5);
            DataGridView_SendList.Add(DataGridView_SendList_5);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_5);

            Label_ID.Add(Label_ID_5);
            TextBox_ID.Add(TextBox_ID_5);
            TextBox_PLCIP.Add(TextBox_PLCIP_5);
            TextBox_PLCPort.Add(TextBox_PLCPort_5);
            TextBox_TCPIP.Add(TextBox_TCPIP_5);
            TextBox_TCPPort.Add(TextBox_TCPPort_5);
            TextBox_T1.Add(TextBox_T1_5);
            TextBox_T3.Add(TextBox_T3_5);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_5);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_5);
            Button_TCPReconnect.Add(Button_TCPReconnect_5);
            Button_PLCReconnect.Add(Button_PLCReconnect_5);
            #endregion

            #region 添加设备_6控件
            deviceList.Add(device6);
            TextBox_Scan.Add(TextBox_Scan_6_1);
            Button_DeviceState.Add(Button_DeviceState_6);
            Button_TCPConnect.Add(Button_TCPConnect_6);
            Button_PLCConnect.Add(Button_PLCConnect_6);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_6);
            DataGridView_SendList.Add(DataGridView_SendList_6);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_6);

            Label_ID.Add(Label_ID_6);
            TextBox_ID.Add(TextBox_ID_6);
            TextBox_PLCIP.Add(TextBox_PLCIP_6);
            TextBox_PLCPort.Add(TextBox_PLCPort_6);
            TextBox_TCPIP.Add(TextBox_TCPIP_6);
            TextBox_TCPPort.Add(TextBox_TCPPort_6);
            TextBox_T1.Add(TextBox_T1_6);
            TextBox_T3.Add(TextBox_T3_6);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_6);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_6);
            Button_TCPReconnect.Add(Button_TCPReconnect_6);
            Button_PLCReconnect.Add(Button_PLCReconnect_6);
            #endregion

            #region 添加设备_7控件
            deviceList.Add(device7);
            TextBox_Scan.Add(TextBox_Scan_7);
            Button_DeviceState.Add(Button_DeviceState_7);
            Button_TCPConnect.Add(Button_TCPConnect_7);
            Button_PLCConnect.Add(Button_PLCConnect_7);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_7);
            DataGridView_SendList.Add(DataGridView_SendList_7);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_7);

            Label_ID.Add(Label_ID_7);
            TextBox_ID.Add(TextBox_ID_7);
            TextBox_PLCIP.Add(TextBox_PLCIP_7);
            TextBox_PLCPort.Add(TextBox_PLCPort_7);
            TextBox_TCPIP.Add(TextBox_TCPIP_7);
            TextBox_TCPPort.Add(TextBox_TCPPort_7);
            TextBox_T1.Add(TextBox_T1_7);
            TextBox_T3.Add(TextBox_T3_7);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_7);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_7);
            Button_TCPReconnect.Add(Button_TCPReconnect_7);
            Button_PLCReconnect.Add(Button_PLCReconnect_7);
            #endregion

            #region 添加设备_8控件
            deviceList.Add(device8);
            TextBox_Scan.Add(TextBox_Scan_8);
            Button_DeviceState.Add(Button_DeviceState_8);
            Button_TCPConnect.Add(Button_TCPConnect_8);
            Button_PLCConnect.Add(Button_PLCConnect_8);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_8);
            DataGridView_SendList.Add(DataGridView_SendList_8);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_8);

            Label_ID.Add(Label_ID_8);
            TextBox_ID.Add(TextBox_ID_8);
            TextBox_PLCIP.Add(TextBox_PLCIP_8);
            TextBox_PLCPort.Add(TextBox_PLCPort_8);
            TextBox_TCPIP.Add(TextBox_TCPIP_8);
            TextBox_TCPPort.Add(TextBox_TCPPort_8);
            TextBox_T1.Add(TextBox_T1_8);
            TextBox_T3.Add(TextBox_T3_8);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_8);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_8);
            Button_TCPReconnect.Add(Button_TCPReconnect_8);
            Button_PLCReconnect.Add(Button_PLCReconnect_8);
            #endregion

            #region 添加设备_9控件
            deviceList.Add(device9);
            TextBox_Scan.Add(TextBox_Scan_9);
            Button_DeviceState.Add(Button_DeviceState_9);
            Button_TCPConnect.Add(Button_TCPConnect_9);
            Button_PLCConnect.Add(Button_PLCConnect_9);
            RichTextBox_WarningBox.Add(RichTextBox_WarningBox_9);
            DataGridView_SendList.Add(DataGridView_SendList_9);
            DataGridView_ReciveList.Add(DataGridView_ReciveList_9);

            Label_ID.Add(Label_ID_9);
            TextBox_ID.Add(TextBox_ID_9);
            TextBox_PLCIP.Add(TextBox_PLCIP_9);
            TextBox_PLCPort.Add(TextBox_PLCPort_9);
            TextBox_TCPIP.Add(TextBox_TCPIP_9);
            TextBox_TCPPort.Add(TextBox_TCPPort_9);
            TextBox_T1.Add(TextBox_T1_9);
            TextBox_T3.Add(TextBox_T3_9);
            TextBox_IdleDelayTime.Add(TextBox_IdleDelayTime_9);
            TextBox_EAP_ALIVE_CHECK_Time.Add(TextBox_EAP_ALIVE_CHECK_Time_9);
            Button_TCPReconnect.Add(Button_TCPReconnect_9);
            Button_PLCReconnect.Add(Button_PLCReconnect_9);
            #endregion

        }
        private void ShowConfigOnForm(Device device)
        {
            int index = deviceList.IndexOf(device);
            Label_ID[index].Text = device.DeviceID.ToString();
            TextBox_ID[index].Text = device.DeviceID.ToString();

            TextBox_PLCIP[index].Text = device.PLC_IP.ToString();
            TextBox_PLCPort[index].Text = device.PLC_Port.ToString();
            TextBox_TCPIP[index].Text = device.TCP_IP.ToString();
            TextBox_TCPPort[index].Text = device.TCP_Port.ToString();
            TextBox_T1[index].Text = device.DelayTime_T1.ToString();
            TextBox_T3[index].Text = device.DelayTime_T3.ToString();
            TextBox_IdleDelayTime[index].Text = device.Idle_Delay_Time.ToString();
            TextBox_EAP_ALIVE_CHECK_Time[index].Text = device.TCPAliveCheckTime.ToString();

            if (device.PLCReConnect)
            {
                Button_PLCReconnect[index].Text = "PLC自动重连启用";
                Button_PLCReconnect[index].BackColor = Color.Green;
            }
            else
            {
                Button_PLCReconnect[index].Text = "PLC自动重连未启用";
                Button_PLCReconnect[index].BackColor = Color.Red;
            }
            if (device.TCPReConnect)
            {
                Button_TCPReconnect[index].Text = "Mes自动重连启用";
                Button_TCPReconnect[index].BackColor = Color.Green;
            }
            else
            {
                Button_TCPReconnect[index].Text = "Mes自动重连未启用";
                Button_TCPReconnect[index].BackColor = Color.Red;
            }


        }

        #endregion

        #region 扫码枪

        //M0=8192
        public void ScanMsgCallBack1_1(string msg)
        {
            AddMSG(device1, "扫码完成");
            Task.Run(() =>
            {
                device1.PLC.WriteCoil("8302", true);
                if (Tool.SBJ_ScanUsing)
                {
                    Thread.Sleep(2000);
                    device1.PLC.WriteCoil("8302", false);
                }
            });
            if (msg == scanDevice1_1.ScanMSG)
            { //防止多次触发
                return;
            }
            if (!msg.Contains("NoRead"))
            {
                scanDevice1_1.ScanMSG = msg;
                if (Tool.SBJ_ScanUsing)
                {
                    Tool.CarrierID_A.Add(msg, 1);
                }
            }
            else
            {
                scanDevice1_1.ScanMSG = "";
            }
            AddMSG(RichTextBox_WarningBox_1, "Port1载具到位");
            if (device1.TCPConnect)
            {
                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "1", "2", msg, out string returnMsg, out string transactionID);
                DeviceSendMsg(device1, data, returnMsg);
                device1.AddSendMsgList(transactionID);
            }

            this.BeginInvoke(new Action(() =>
            {
                TextBox_Scan_1_1.Text = msg;
            }));
            device1.PLC.WriteUnicodeString("2000", msg, 10);
        }
        public void ScanMsgCallBack1_2(string msg)
        {
            Task.Run(() =>
            {
                device1.PLC.WriteCoil("8303", true);
                if (Tool.SBJ_ScanUsing)
                {
                    Thread.Sleep(2000);
                    device1.PLC.WriteCoil("8303", false);
                }
            });

            if (msg == scanDevice1_2.ScanMSG)
            {
                //防止多次触发
                return;
            }
            if (!msg.Contains("NoRead"))
            {
                scanDevice1_2.ScanMSG = msg;
                if (Tool.SBJ_ScanUsing)
                {
                    Tool.CarrierID_B.Add(msg, 1);
                }
            }
            else
            {
                scanDevice1_2.ScanMSG = "";
            }

            AddMSG(RichTextBox_WarningBox_1, "Port5载具到位");
            if (device1.TCPConnect)
            {
                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "5", "2", msg, out string returnMsg, out string transactionID);
                DeviceSendMsg(device1, data, returnMsg);
                device1.AddSendMsgList(transactionID);
            }

            this.BeginInvoke(new Action(() =>
            {
                TextBox_Scan_1_2.Text = msg;
            }));
            device1.PLC.WriteUnicodeString("2100", msg, 10);

        }
        public void ScanMsgCallBack6_1(string msg)
        {
            if (msg.StartsWith("ER"))
            {
                return;
            }
            this.BeginInvoke(new Action(() =>
            {
                TextBox_Scan_6_1.Text = msg;
            }));
            if (!msg.Contains("NoRead"))
            {
                scanDevice6_1.ScanMSG = msg;
            }
            else
            {
                scanDevice6_1.ScanMSG = "";
                if (Tool.ICT_ScanUsing == true)
                {
                    //写点不让ICT进板，PLC还没改
                }
            }

            if (device6.TCPConnect)
            {
                byte[] data = SendEvent.JOB_MOVE_IN_REQUEST(device6, scanDevice6_1.ScanMSG, "", out string Msg, out string transactionID);
                DeviceSendMsg(device6, data, Msg);
                device6.AddSendMsgList(transactionID);
            }
        }
        public void ScanMsgCallBack6_2(string msg)
        {
            if (msg.StartsWith("ER"))
            {
                return;
            }
            this.BeginInvoke(new Action(() =>
            {
                TextBox_Scan_6_2.Text = msg;
            }));
            if (!msg.Contains("NoRead"))
            {
                scanDevice6_2.ScanMSG = msg;
                device6.PLC.Write("1001", 22);//扫码完成
            }
            else
            {
                scanDevice6_2.ScanMSG = "";
                if (Tool.FCT_ScanUsing == false)
                {
                    device6.PLC.Write("1001", 22);//扫码完成
                }
            }
            device6.PLC.WriteUnicodeString("5000", msg, 15);

        }
        public void ScanDeviceConnectServer()
        {
            #region 上板机扫码枪1
            Task.Run(() =>
            {
                int res = scanDevice1_1.ConnectSocket();
                this.BeginInvoke(new Action(() =>
                {
                    if (res == 0)
                    {
                        Button_Scan_1_1.Text = "扫码枪1";
                        Button_Scan_1_1.BackColor = Color.Green;
                    }
                    else
                    {
                        Button_Scan_1_1.BackColor = Color.Red;
                    }
                }));
                scanDevice1_1.SetMsgCallBackHandle(ScanMsgCallBack1_1);
            });

            #endregion

            #region 上板机扫码枪2
            Task.Run(() =>
            {
                int res = scanDevice1_2.ConnectSocket();
                this.BeginInvoke(new Action(() =>
                {
                    if (res == 0)
                    {
                        Button_Scan_1_2.Text = "扫码枪2";
                        Button_Scan_1_2.BackColor = Color.Green;
                    }
                    else
                    {
                        Button_Scan_1_2.BackColor = Color.Red;
                    }
                }));
                scanDevice1_2.SetMsgCallBackHandle(ScanMsgCallBack1_2);
            });
            #endregion

            #region ICT出板
            Task.Run(() =>
            {
                int res = scanDevice6_2.ConnectSocket();
                this.BeginInvoke(new Action(() =>
                {
                    if (res == 0)
                    {
                        Button_Scan_6_2.Text = "扫码枪2";
                        Button_Scan_6_2.BackColor = Color.Green;
                    }
                    else
                    {
                        Button_Scan_6_2.BackColor = Color.Red;
                    }
                }));
                scanDevice6_2.SetMsgCallBackHandle(ScanMsgCallBack6_2);
            });
            #endregion

            #region ICT进板
            Task.Run(() =>
            {
                int res = scanDevice6_1.ConnectSocket();
                this.BeginInvoke(new Action(() =>
                {
                    if (res == 0)
                    {
                        Button_Scan_6_1.Text = "扫码枪1";
                        Button_Scan_6_1.BackColor = Color.Green;
                    }
                    else
                    {
                        Button_Scan_6_1.BackColor = Color.Red;
                    }
                }));
                scanDevice6_1.SetMsgCallBackHandle(ScanMsgCallBack6_1);
            });
            #endregion

        }

        /// <summary>
        /// 显示参数
        /// </summary>
        public void ScanDeviceInfoOnForm()
        {
            textBox5.Text = scanDevice1_1.TCP_IP;
            textBox4.Text = scanDevice1_1.TCP_Port.ToString();

            textBox7.Text = scanDevice1_2.TCP_IP;
            textBox6.Text = scanDevice1_2.TCP_Port.ToString();

            textBox20.Text = scanDevice6_1.TCP_IP;
            textBox19.Text = scanDevice6_1.TCP_Port.ToString();

            textBox18.Text = scanDevice6_2.TCP_IP;
            textBox17.Text = scanDevice6_2.TCP_Port.ToString();
        }


        #endregion

        #region   接收Mes格式////////接收Mes格式////////接收Mes格式////////接收Mes格式////////接收Mes格式////////接收Mes格式////////接收Mes格式////////接收Mes格式////////接收Mes格式////////
        public void ReciveMsgCallBack1(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[0], msg, "Recive");
            Tool.SaveLog(device1, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device1, msg);
        }
        public void ReciveMsgCallBack2(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[1], msg, "Recive");
            Tool.SaveLog(device2, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device2, msg);
        }
        public void ReciveMsgCallBack3(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[2], msg, "Recive");
            Tool.SaveLog(device3, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device3, msg);
        }
        public void ReciveMsgCallBack4(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[3], msg, "Recive");
            Tool.SaveLog(device4, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device4, msg);
        }
        public void ReciveMsgCallBack5(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[4], msg, "Recive");
            Tool.SaveLog(device5, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device5, msg);
        }
        public void ReciveMsgCallBack6(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[5], msg, "Recive");
            Tool.SaveLog(device6, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device6, msg);
        }
        public void ReciveMsgCallBack7(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[6], msg, "Recive");
            Tool.SaveLog(device7, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device7, msg);
        }
        public void ReciveMsgCallBack8(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[7], msg, "Recive");
            Tool.SaveLog(device8, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device8, msg);
        }
        public void ReciveMsgCallBack9(string msg)
        {
            msg = msg.Substring(4);
            AddInfoOnDataGridView(DataGridView_SendList[8], msg, "Recive");
            Tool.SaveLog(device9, LogMod.Mes交互记录.ToString(), "[Recive]" + "\r\n" + msg);
            CheckMsgEvent(device9, msg);
        }

        /// <summary>
        /// 收到信息的回调
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="device"></param>
        private void CheckMsgEvent(Device device, string msg)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(msg);
            XmlNode root = xmlDocument.DocumentElement;
            string MessageName = "";
            string transactionID = "";
            try
            {
                XmlNode MESSAGENAME = root.SelectSingleNode("Header/MESSAGENAME");
                MessageName = MESSAGENAME.InnerText;

                //此处执行一次回收队列清除
                transactionID = root.SelectSingleNode("Header/TRANSACTIONID").InnerText;
                if (transactionID != "")
                {
                    //执行回复队列清除
                    lock (this)
                    {
                        foreach (var item in device.SendMsgList1)
                        {
                            if (item.Key == transactionID)
                            {
                                device.SendMsgList1.Remove(item.Key);
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {

            }
            switch (MessageName)
            {
                //指令为修改本地时间为指定的值
                case "DATE_TIME_CALIBRATION_COMMAND":
                    try
                    {
                        string time = root.SelectSingleNode("Body/DateTime").InnerText;
                        int year = Convert.ToInt32(time.Substring(0, 2)) + 2000;
                        int mon = Convert.ToInt32(time.Substring(2, 2));
                        int day = Convert.ToInt32(time.Substring(4, 2));
                        int hour = Convert.ToInt32(time.Substring(6, 2));
                        int min = Convert.ToInt32(time.Substring(8, 2));
                        int second = Convert.ToInt32(time.Substring(10));
                        DateTime dateTime = new DateTime(year, mon, day, hour, min, second);
                        DateTimeSynchronization.SetLocalDateTime(dateTime);
                        byte[] data = SendEvent.ReturnMsg(device, "DATE_TIME_CALIBRATION_COMMAND_R", transactionID, "000000", "", out string returnMsg);
                        DeviceSendMsg(device, data, returnMsg);
                    }
                    catch
                    {
                        byte[] data = SendEvent.ReturnMsg(device, "DATE_TIME_CALIBRATION_COMMAND_R", transactionID, "000099", "Body解析错误", out string returnMsg);
                        DeviceSendMsg(device, data, returnMsg);
                    }

                    break;
                //CIM信息通知
                case "MESSAGE_DISPLAY_COMMAND":
                    try
                    {
                        int index = deviceList.IndexOf(device);
                        string MessageText = root.SelectSingleNode("Body/MessageText").InnerText;
                        AddCIMInfoOnDataGridView(DataGridView_ReciveList[index], MessageText);
                        //
                        //执行一次PLC发送数据的方法，让触摸屏显示CIM信息
                        //
                        byte[] data = SendEvent.ReturnMsg(device, "MESSAGE_DISPLAY_COMMAND_R", transactionID, "000000", "", out string returnMsg);
                        DeviceSendMsg(device, data, returnMsg);
                    }
                    catch
                    {
                        byte[] data = SendEvent.ReturnMsg(device, "MESSAGE_DISPLAY_COMMAND_R", transactionID, "000099", "Body解析错误", out string returnMsg);
                        DeviceSendMsg(device, data, returnMsg);
                    }
                    break;
                //制程停止信号
                case "PROCESS_STOP_COMMAND":
                    try
                    {
                        int index = deviceList.IndexOf(device);
                        string ProcessStop = root.SelectSingleNode("Body/ProcessStop").InnerText;
                        if (ProcessStop == "1")
                        {
                            //执行设备停止

                            byte[] data = SendEvent.ReturnMsg(device, "PROCESS_STOP_COMMAND_R", transactionID, "000000", "", out string returnMsg);
                            DeviceSendMsg(device, data, returnMsg);
                        }
                        else if (ProcessStop == "2")
                        {
                            //执行设备开始

                            byte[] data = SendEvent.ReturnMsg(device, "PROCESS_STOP_COMMAND_R", transactionID, "000000", "", out string returnMsg);
                            DeviceSendMsg(device, data, returnMsg);
                        }
                        else
                        {
                            byte[] data = SendEvent.ReturnMsg(device, "PROCESS_STOP_COMMAND_R", transactionID, "000099", "Body解析错误", out string returnMsg);
                            DeviceSendMsg(device, data, returnMsg);
                        }

                    }
                    catch
                    {
                        byte[] data = SendEvent.ReturnMsg(device, "PROCESS_STOP_COMMAND_R", transactionID, "000099", "Body解析错误", out string returnMsg);
                        DeviceSendMsg(device, data, returnMsg);
                    }
                    break;

                //配方修改允许,,,现场暂时停用
                //case "RECIPE_MODIFY_REPORT_R":
                //    try
                //    {
                //        //收到回复，执行配方修改动作
                //        //由于9台设备同时进行接收，需增加一个全局方法进行单次配方修改
                //        //每台设备单独执行PLC设备控制
                //    }
                //    catch
                //    {

                //    }
                //    break;

                //配方切换
                case "RECIPE_PARAMETER_DOWNLOAD_COMMAND":
                    try
                    {
                        int index = deviceList.IndexOf(device);
                        string RecipeID = root.SelectSingleNode("Body/RecipeID").InnerText;
                        byte[] data;
                        //执行配方切换
                        if (device.DeviceState == 1 || device.DeviceState == 3)
                        {
                            //执行PLC控制
                            //①停止向前工序机台发要板信号
                            //②完成机台内产品的生产（有在制品）或空跑检测轨道是否有异物（无在制品）


                            data = SendEvent.ReturnMsg(device, "RECIPE_PARAMETER_DOWNLOAD_COMMAND_R", transactionID, "000000", "", out string returnMsg);
                            DeviceSendMsg(device, data, returnMsg);


                            //执行配方ID报告
                            data = SendEvent.CURRENT_RECIPE_ID_REPORT(device, out string msg1, out string transactionID1);
                            DeviceSendMsg(device, data, msg1);
                            device.AddSendMsgList(transactionID1);
                        }
                        else
                        {
                            data = SendEvent.ReturnMsg(device, "RECIPE_PARAMETER_DOWNLOAD_COMMAND_R", transactionID, "000099", "设备未处于运行、待机状态", out string returnMsg);
                            DeviceSendMsg(device, data, returnMsg);
                            return;
                        }
                    }
                    catch
                    {
                        byte[] data = SendEvent.ReturnMsg(device, "RECIPE_PARAMETER_DOWNLOAD_COMMAND_R", transactionID, "000099", "Body解析错误", out string returnMsg);
                        DeviceSendMsg(device, data, returnMsg);
                    }
                    break;
                case "CARRIER_TRX_CMD_FROM_VEHICLE_REPORT":
                    try
                    {
                        int index = deviceList.IndexOf(device);
                        string Command1 = root.SelectSingleNode("Body/Command1").InnerText;
                        string code = "";
                        string errormsg = "";
                        string D = "";

                        switch (Command1)
                        {
                            case "1"://AGV请求卸货,上板机上料
                                Tool.AGV_Pos = Tool.AGV_Load_Pos;
                                if (Tool.AGV_Load_Pos == 1)
                                {
                                    if (Tool.SBJPortState["1"] == 1 && Tool.SBJPortState["2"] == 1)
                                    {
                                        code = "000001";
                                        D = "123";
                                    }
                                    else
                                    {
                                        code = "000099";
                                        errormsg = "当前A轨下层有料";
                                    }
                                }
                                else if (Tool.AGV_Load_Pos == 2)
                                {
                                    if (Tool.SBJPortState["5"] == 1 && Tool.SBJPortState["6"] == 1)
                                    {
                                        code = "000001";
                                        D = "133";
                                    }
                                    else
                                    {
                                        code = "000099";
                                        errormsg = "当前B轨下层有料";
                                    }
                                }

                                break;
                            case "2"://AGV请求取货,上板机卸料
                                Tool.AGV_Pos = Tool.AGV_UnLoad_Pos;
                                if (Tool.AGV_Load_Pos == 1)
                                {
                                    if (Tool.SBJPortState["3"] == 1 && Tool.SBJPortState["4"] == 1)
                                    {
                                        code = "000002";
                                        D = "124";
                                    }
                                    else
                                    {
                                        code = "000099";
                                        errormsg = "当前A轨上层无料";
                                    }
                                }
                                else if (Tool.AGV_Load_Pos == 2)
                                {
                                    if (Tool.SBJPortState["7"] == 1 && Tool.SBJPortState["8"] == 1)
                                    {
                                        code = "000002";
                                        D = "134";
                                    }
                                    else
                                    {
                                        code = "000099";
                                        errormsg = "当前B轨上层无料";
                                    }
                                }
                                break;
                            case "3"://AGV请求离开
                                code = "000003";
                                break;
                        }

                        byte[] data = SendEvent.ReturnMsg(device, "CARRIER_TRX_CMD_FROM_VEHICLE_REPORT_R", transactionID, code, errormsg, out string returnMsg);
                        DeviceSendMsg(device, data, returnMsg);
                        //  device1.PLC.Write(D, 1);

                    }
                    catch
                    {
                        byte[] data = SendEvent.ReturnMsg(device, "CARRIER_TRX_CMD_FROM_VEHICLE_REPORT_R", transactionID, "000099", "Body解析错误", out string returnMsg);
                        DeviceSendMsg(device, data, returnMsg);
                    }
                    break;

            }


        }

        #endregion

        #region  设备通讯状态变化////////设备通讯状态变化////////设备通讯状态变化////////设备通讯状态变化////////设备通讯状态变化////////设备通讯状态变化////////设备通讯状态变化////////


        #endregion

        #region  设备对象的线程////// 设备对象的线程////// 设备对象的线程////// 设备对象的线程////// 设备对象的线程////// 设备对象的线程////// 设备对象的线程////// 设备对象的线程//////

        #region 设备运行状态

        #region  禾旭
        public void TaskRun1()
        {
            ///上板机
            ///
            int DeviceState = 0;
            //Stopwatch stopWatch = new Stopwatch();
            while (true)
            {
                //stopWatch.Start();
                if (device1.PLCConnect == false)
                {
                    continue;
                }
                //是否故障
                int D120 = Convert.ToInt32(device1.PLC.ReadInt16("120").Content);
                if (D120 > 0)
                {
                    DeviceState = 2;//故障中
                }
                else
                {
                    bool M100 = device1.PLC.ReadCoil("8292").Content;
                    bool M600 = device1.PLC.ReadCoil("8792").Content;
                    if (M100 || M600)
                    {
                        DeviceState = 1;//运行
                    }
                    else
                    {
                        DeviceState = 4;//停止
                    }
                }

                if (DeviceState != device1.DeviceState)
                {
                    if (device1.DeviceState == 2)
                    {
                        foreach (var item in device1.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device1, 2, 2, item, device1.errorList[item - 1], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device1, data, alarmMsg);
                            Tool.SaveLog(device1, LogMod.运行记录.ToString(), "报警消除==>" + device1.errorList[item - 1]);
                            device1.AddSendMsgList(transactionID_1);
                        }
                        device1.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {
                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_1.BackColor = Color.Green;
                                Button_DeviceState_1.Text = "运行中";
                            }));

                            device1.DeviceState = DeviceState;
                            Tool.SaveLog(device1, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device1.DeviceState, device1))
                            {
                                try
                                {
                                    if (!device1.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device1, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device1, data, msg);
                                    device1.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device1.DeviceState);
                                    device1.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device1.IdleDelay == false)
                            {
                                device1.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device1.Idle_WaitTime += 100;
                                        if (device1.Idle_WaitTime >= device1.Idle_Delay_Time)
                                        {
                                            device1.Idle_WaitTime = 0;
                                            device1.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_1.BackColor = Color.Yellow;
                                                Button_DeviceState_1.Text = "待机中";
                                            }));
                                            device1.DeviceState = 2;
                                            Tool.SaveLog(device1, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device1.DeviceState, device1))
                                            {
                                                try
                                                {
                                                    if (!device1.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device1, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device1, data, msg);
                                                    device1.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device1.DeviceState);
                                                    device1.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device1.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_1.BackColor = Color.Orange;
                                Button_DeviceState_1.Text = "停止中";
                            }));
                            device1.DeviceState = DeviceState;

                            Tool.SaveLog(device1, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device1.DeviceState, device1))
                            {
                                try
                                {
                                    if (!device1.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device1, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device1, data, msg);
                                    device1.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device1.DeviceState);
                                    device1.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_1.BackColor = Color.Red;
                                Button_DeviceState_1.Text = "故障中";
                            }));

                            device1.DeviceState = DeviceState;
                            Tool.SaveLog(device1, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());
                            int errorNum = D120;
                            AddMSG(RichTextBox_WarningBox_1, device1.errorList[errorNum - 1]);
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device1.DeviceState, device1))
                            {
                                if (!device1.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device1, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device1, data, msg);
                                    device1.AddSendMsgList(transactionID);
                                    if (errorNum > 0)
                                    {
                                        device1.errorCode.Add(errorNum);
                                        data = SendEvent.ALARM_REPORT(device1, 1, 2, errorNum, device1.errorList[errorNum - 1], out string alarmMsg, out string transactionID_1);
                                        DeviceSendMsg(device1, data, alarmMsg);
                                        Tool.SaveLog(device1, LogMod.运行记录.ToString(), "报警记录==>" + device1.errorList[errorNum - 1]);
                                        device1.AddSendMsgList(transactionID_1);
                                    }
                                    device1.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device1.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;

                    }
                }
                else
                {

                }
                //stopWatch.Stop();
                //AddMSG(RichTextBox_WarningBox_1, stopWatch.ElapsedMilliseconds.ToString());
                //stopWatch.Reset();
                Thread.Sleep(500);
            }
        }
        public void TaskRun4()
        {
            ///暂存机
            ///
            int DeviceState = 0;
            while (true)
            {
                if (device4.PLCConnect == false)
                {
                    continue;
                }

                //是否故障
                int D120 = Convert.ToInt32(device4.PLC.ReadInt16("120").Content);
                if (D120 > 0)
                {
                    DeviceState = 2;//故障中
                }
                else
                {
                    bool M100 = device4.PLC.ReadCoil("8292").Content;

                    if (M100)
                    {
                        DeviceState = 1;//运行
                    }
                    else
                    {
                        DeviceState = 4;//停止
                    }
                }
                if (DeviceState != device4.DeviceState)
                {
                    if (device4.DeviceState == 2)
                    {
                        foreach (var item in device4.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device4, 2, 2, item, device4.errorList[item - 1], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device4, data, alarmMsg);
                            Tool.SaveLog(device4, LogMod.运行记录.ToString(), "报警消除==>" + device4.errorList[item - 1]);
                            device4.AddSendMsgList(transactionID_1);
                        }
                        device4.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {
                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_4.BackColor = Color.Green;
                                Button_DeviceState_4.Text = "运行中";
                            }));

                            device4.DeviceState = DeviceState;
                            Tool.SaveLog(device4, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device4.DeviceState, device4))
                            {
                                try
                                {
                                    if (!device4.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device4, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device4, data, msg);

                                    device4.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device4.DeviceState);
                                    device4.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device4.IdleDelay == false)
                            {
                                device4.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device4.Idle_WaitTime += 100;
                                        if (device4.Idle_WaitTime >= device4.Idle_Delay_Time)
                                        {
                                            device4.Idle_WaitTime = 0;
                                            device4.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_4.BackColor = Color.Yellow;
                                                Button_DeviceState_4.Text = "待机中";
                                            }));
                                            device4.DeviceState = 2;
                                            Tool.SaveLog(device4, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device4.DeviceState, device4))
                                            {
                                                try
                                                {
                                                    if (!device4.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device4, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device4, data, msg);

                                                    device4.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device4.DeviceState);
                                                    device4.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device4.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_4.BackColor = Color.Orange;
                                Button_DeviceState_4.Text = "停止中";
                            }));

                            device4.DeviceState = DeviceState;
                            Tool.SaveLog(device4, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device4.DeviceState, device4))
                            {
                                try
                                {
                                    if (!device4.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device4, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device4, data, msg);
                                    device4.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device4.DeviceState);
                                    device4.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_4.BackColor = Color.Red;
                                Button_DeviceState_4.Text = "故障中";
                            }));

                            device4.DeviceState = DeviceState;
                            Tool.SaveLog(device4, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());
                            int errorNum = D120;
                            AddMSG(RichTextBox_WarningBox_4, device4.errorList[errorNum - 1]);
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device4.DeviceState, device4))
                            {
                                if (!device4.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device4, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device4, data, msg);
                                    device4.AddSendMsgList(transactionID);

                                    if (errorNum > 0)
                                    {
                                        device4.errorCode.Add(errorNum);
                                        data = SendEvent.ALARM_REPORT(device4, 1, 2, errorNum, device4.errorList[errorNum - 1], out string alarmMsg, out string transactionID_4);
                                        DeviceSendMsg(device4, data, alarmMsg);
                                        Tool.SaveLog(device4, LogMod.运行记录.ToString(), "报警记录==>" + device4.errorList[errorNum - 1]);
                                        device4.AddSendMsgList(transactionID_4);
                                    }
                                    device4.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device4.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;

                    }
                }
                else
                {

                }
                Thread.Sleep(500);
            }
        }
        public void TaskRun8()
        {
            ///翻板机
            ///

            int DeviceState = 0;
            while (true)
            {
                if (device8.PLCConnect == false)
                {
                    continue;
                }

                //是否故障
                int D120 = Convert.ToInt32(device8.PLC.ReadInt16("120").Content);
                if (D120 > 0)
                {
                    DeviceState = 2;//故障中
                }
                else
                {

                    bool M100 = device8.PLC.ReadCoil("8292").Content;

                    if (M100)
                    {
                        DeviceState = 1;//运行
                    }
                    else
                    {
                        DeviceState = 4;//停止
                    }
                }
                if (DeviceState != device8.DeviceState)
                {
                    if (device8.DeviceState == 2)
                    {
                        foreach (var item in device8.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device8, 2, 2, item, device8.errorList[item - 1], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device8, data, alarmMsg);
                            Tool.SaveLog(device8, LogMod.运行记录.ToString(), "报警消除==>" + device8.errorList[item - 1]);
                            device8.AddSendMsgList(transactionID_1);
                        }
                        device8.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {
                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_8.BackColor = Color.Green;
                                Button_DeviceState_8.Text = "运行中";
                            }));

                            device8.DeviceState = DeviceState;
                            Tool.SaveLog(device8, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device8.DeviceState, device8))
                            {
                                try
                                {
                                    if (!device8.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device8, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device8, data, msg);

                                    device8.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device8.DeviceState);
                                    device8.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device8.IdleDelay == false)
                            {
                                device8.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device8.Idle_WaitTime += 100;
                                        if (device8.Idle_WaitTime >= device8.Idle_Delay_Time)
                                        {
                                            device8.Idle_WaitTime = 0;
                                            device8.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_8.BackColor = Color.Yellow;
                                                Button_DeviceState_8.Text = "待机中";
                                            }));
                                            device8.DeviceState = 2;
                                            Tool.SaveLog(device8, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device8.DeviceState, device8))
                                            {
                                                try
                                                {
                                                    if (!device8.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device8, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device8, data, msg);

                                                    device8.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device8.DeviceState);
                                                    device8.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device8.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_8.BackColor = Color.Orange;
                                Button_DeviceState_8.Text = "停止中";
                            }));

                            device8.DeviceState = DeviceState;
                            Tool.SaveLog(device8, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device8.DeviceState, device8))
                            {
                                try
                                {
                                    if (!device8.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device8, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device8, data, msg);
                                    device8.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device8.DeviceState);
                                    device8.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_8.BackColor = Color.Red;
                                Button_DeviceState_8.Text = "故障中";
                            }));

                            device8.DeviceState = DeviceState;
                            Tool.SaveLog(device8, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());
                            int errorNum = D120;
                            AddMSG(RichTextBox_WarningBox_8, device8.errorList[errorNum - 1]);

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device8.DeviceState, device8))
                            {
                                if (!device8.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device8, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device8, data, msg);
                                    device8.AddSendMsgList(transactionID);


                                    if (errorNum > 0)
                                    {
                                        device8.errorCode.Add(errorNum);
                                        data = SendEvent.ALARM_REPORT(device8, 1, 2, errorNum, device8.errorList[errorNum - 1], out string alarmMsg, out string transactionID_8);
                                        DeviceSendMsg(device8, data, alarmMsg);
                                        Tool.SaveLog(device8, LogMod.运行记录.ToString(), "报警记录==>" + device8.errorList[errorNum - 1]);
                                        device8.AddSendMsgList(transactionID_8);
                                    }
                                    device8.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device8.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;

                    }
                }
                else
                {

                }
                Thread.Sleep(500);
            }
        }

        #endregion

        #region 方科讯
        public void TaskRun6()
        {
            ///ICT

            int DeviceState = 0;
            int D0 = 0;
            int D20 = 0;
            int D21 = 0;
            bool login = false;
            bool logout = false;
            bool FirstRead = false;
            bool SecondRead = false;

            int airCylinder_Count = 0;
            int inPCB_Motor = 0;
            int outPCB_Motor = 0;

            string NumberSystem = "";
            string Sorting = "";

            while (true)
            {
                if (device6.PLCConnect == false)
                {
                    continue;
                }
                //D0=0 STOP  D0=1 IDLE  D0=2 RUN
                //是否故障
                D20 = device6.PLC.ReadInt16("20").Content;
                D21 = device6.PLC.ReadInt16("21").Content;
                if (D20 > 0 || D21 > 0)
                {
                    DeviceState = 2;//故障中
                }
                else
                {
                    D0 = device6.PLC.ReadInt16("0").Content;
                    switch (D0)
                    {
                        case 0:
                            DeviceState = 4;//停止中
                            break;
                        case 1:
                            DeviceState = 3;//待料中
                            break;
                        case 2:
                            DeviceState = 1;//运行中
                            break;

                    }
                }

                if (DeviceState != 2)
                {
                    device6.IdleDelay = false;
                    device6.Idle_WaitTime = 0;
                }
                if (DeviceState != device6.DeviceState)
                {
                    if (device6.DeviceState == 2)
                    {
                        foreach (var item in device6.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device6, 2, 2, item + 1, device6.errorList[item], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device6, data, alarmMsg);
                            Tool.SaveLog(device6, LogMod.运行记录.ToString(), "报警消除==>" + device6.errorList[item - 1]);
                            device6.AddSendMsgList(transactionID_1);
                        }
                        device6.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {
                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_6.BackColor = Color.Green;
                                Button_DeviceState_6.Text = "运行中";
                            }));

                            device6.DeviceState = DeviceState;
                            Tool.SaveLog(device6, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device6.DeviceState, device6))
                            {
                                try
                                {
                                    if (!device6.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device6, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device6, data, msg);

                                    device6.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device6.DeviceState);
                                    device6.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device6.IdleDelay == false)
                            {
                                device6.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device6.Idle_WaitTime += 100;
                                        if (device6.Idle_WaitTime >= device6.Idle_Delay_Time)
                                        {
                                            device6.Idle_WaitTime = 0;
                                            device6.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_6.BackColor = Color.Yellow;
                                                Button_DeviceState_6.Text = "待机中";
                                            }));
                                            device6.DeviceState = 2;
                                            Tool.SaveLog(device6, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device6.DeviceState, device6))
                                            {
                                                try
                                                {
                                                    if (!device6.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device6, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device6, data, msg);

                                                    device6.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device6.DeviceState);
                                                    device6.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device6.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_6.BackColor = Color.Orange;
                                Button_DeviceState_6.Text = "停止中";
                            }));

                            device6.DeviceState = DeviceState;
                            Tool.SaveLog(device6, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device6.DeviceState, device6))
                            {
                                try
                                {
                                    if (!device6.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device6, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device6, data, msg);
                                    device6.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device6.DeviceState);
                                    device6.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_6.BackColor = Color.Red;
                                Button_DeviceState_6.Text = "故障中";
                            }));

                            device6.DeviceState = DeviceState;
                            Tool.SaveLog(device6, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());

                            //方科讯特有报警点位//ICT&FCT
                            //报警记录见Tool类注释
                            // int errorNum = 0;
                            List<int> errorNum = new List<int>();
                            try
                            {

                                if (D20 > 0)
                                {
                                    //errorNum = Convert.ToInt32(Math.Log(D20, 2));
                                    CheckErrorList(ref errorNum, ref D20, 1);
                                }
                                if (D21 > 0)
                                {
                                    //errorNum = Convert.ToInt32(Math.Log(D21, 2)) + Convert.ToInt32(Math.Log(32768, 2) + 1);
                                    CheckErrorList(ref errorNum, ref D21, 2);
                                }
                            }
                            catch
                            {

                            }
                            foreach (int item in errorNum)
                            {
                                AddMSG(RichTextBox_WarningBox_6, device6.errorList[item]);
                            }

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device6.DeviceState, device6))
                            {
                                if (!device6.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device6, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device6, data, msg);
                                    device6.AddSendMsgList(transactionID);
                                    if (errorNum.Count >= 0)
                                    {
                                        foreach (int item in errorNum)
                                        {
                                            device6.errorCode.Add(item);
                                            data = SendEvent.ALARM_REPORT(device6, 1, 2, item + 1, device6.errorList[item], out string alarmMsg, out string transactionID_6);
                                            DeviceSendMsg(device6, data, alarmMsg);
                                            Tool.SaveLog(device6, LogMod.运行记录.ToString(), "报警记录==>" + device6.errorList[item]);
                                            device6.AddSendMsgList(transactionID_6);
                                        }
                                    }
                                    device6.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device6.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
                else
                {

                }
                // 读取设备的登入登录状态
                if(device6.PLC.ReadCoil("8694").Content==false && logout==false)
                {
                    logout =true;
                    login = false;
                    device6.LoginState = false;
                    string msg;
                    string id;
                    byte[] data = SendEvent.Operator_Login_Logout(device6, "001102", out msg, out id);
                    DeviceSendMsg(device6, data, msg);


                }

                if(device6.PLC.ReadCoil("8694").Content == true && login == false)
                {
                    login = true;
                    logout = false;
                    device6.LoginState = true;

                    string msg;
                    string id;
                    byte[] data = SendEvent.Operator_Login_Logout(device6, "001101", out msg, out id);
                    DeviceSendMsg(device6, data, msg);
                }
                if(device6.Sorting != device6.LastTime_Sorting)
                {
                    Sorting = device6.Sorting;
                    NumberSystem = "HEX";
                }
                else
                {
                    Sorting = " ";
                }

                //第一次读取进板电机运行时间和次数
                if(device6.PLC.ReadCoil("8695").Content==true && FirstRead == false)
                {
                    FirstRead = true;
                    airCylinder_Count = 1;
                    inPCB_Motor = device6.PLC.ReadInt16("32").Content;
                }

                //第二次出板的时候电机的运行时间
                if(device6.PLC.ReadCoil("8696").Content==true  && SecondRead == false)
                {
                    SecondRead = true;
                    outPCB_Motor = device6.PLC.ReadInt16("34").Content;
                    string msg;
                    string id;
                    byte[] date = SendEvent.UTILITY_DATA_REPORT_ICT(device6, airCylinder_Count.ToString(), inPCB_Motor.ToString(), outPCB_Motor.ToString(), NumberSystem, Sorting, out msg, out id);
                    DeviceSendMsg(device6, date, msg);
                    device6.LastTime_Sorting = device6.Sorting;
                }

                if(device6.PLC.ReadCoil("8695").Content == false) FirstRead = false;
                if(device6.PLC.ReadCoil("8696").Content == false) SecondRead = false;

                Thread.Sleep(500);
            }
        }
        public void TaskRun7()
        {
            ///FCT
            int DeviceState = 0;
            int D0 = 0;
            int D1 = 0;
            int D20 = 0;
            int D21 = 0;
            bool login = false;
            bool logout = false;

            bool FirstRead1 = false;
            bool SecondRead1 = false;

            bool FirstRead2 = false;
            bool SecondRead2 = false;

            int airCylinder_Count1 = 0;
            int inPCB_Motor1 = 0;
            int outPCB_Motor1 = 0;

            int airCylinder_Count2 = 0;
            int inPCB_Motor2 = 0;
            int outPCB_Motor2 = 0;

            string NumberSystem = "";
            string Sorting = "";


            while (true)
            {
                if (device6.PLCConnect == false)
                {
                    continue;
                }
                //D0=0 STOP  D0=1 IDLE  D0=2 RUN
                //是否故障
                D20 = device7.PLC.ReadInt16("20").Content;
                D21 = device7.PLC.ReadInt16("21").Content;
                if (D20 > 0 || D21 > 0)
                {
                    DeviceState = 2;//故障中
                }
                else
                {
                    D0 = device7.PLC.ReadInt16("0").Content;
                    D1 = device7.PLC.ReadInt16("1").Content;

                    if (D0 == 2 || D1 == 2)
                    {
                        //运行
                        DeviceState = 1;
                    }
                    else
                    {
                        if (D0 == 1 || D1 == 1)
                        {
                            //待料
                            DeviceState = 3;
                        }
                        else
                        {
                            //停止
                            DeviceState = 4;
                        }
                    }
                }

                if (DeviceState != 2)
                {
                    device7.IdleDelay = false;
                    device7.Idle_WaitTime = 0;
                }
                if (DeviceState != device7.DeviceState)
                {
                    if (device7.DeviceState == 2)
                    {
                        foreach (var item in device7.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device7, 2, 2, item + 1, device7.errorList[item], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device7, data, alarmMsg);
                            Tool.SaveLog(device7, LogMod.运行记录.ToString(), "报警消除==>" + device7.errorList[item - 1]);
                            device7.AddSendMsgList(transactionID_1);
                        }
                        device7.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {
                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_7.BackColor = Color.Green;
                                Button_DeviceState_7.Text = "运行中";
                            }));

                            device7.DeviceState = DeviceState;
                            Tool.SaveLog(device7, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device7.DeviceState, device7))
                            {
                                try
                                {
                                    if (!device7.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device7, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device7, data, msg);

                                    device7.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device7.DeviceState);
                                    device7.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device7.IdleDelay == false)
                            {
                                device7.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device7.Idle_WaitTime += 100;
                                        if (device7.Idle_WaitTime >= device7.Idle_Delay_Time)
                                        {
                                            device7.Idle_WaitTime = 0;
                                            device7.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_7.BackColor = Color.Yellow;
                                                Button_DeviceState_7.Text = "待机中";
                                            }));
                                            device7.DeviceState = 2;
                                            Tool.SaveLog(device7, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device7.DeviceState, device7))
                                            {
                                                try
                                                {
                                                    if (!device7.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device7, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device7, data, msg);

                                                    device7.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device7.DeviceState);
                                                    device7.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device7.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_7.BackColor = Color.Orange;
                                Button_DeviceState_7.Text = "停止中";
                            }));

                            device7.DeviceState = DeviceState;
                            Tool.SaveLog(device7, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device7.DeviceState, device7))
                            {
                                try
                                {
                                    if (!device7.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device7, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device7, data, msg);
                                    device7.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device7.DeviceState);
                                    device7.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_7.BackColor = Color.Red;
                                Button_DeviceState_7.Text = "故障中";
                            }));

                            device7.DeviceState = DeviceState;
                            Tool.SaveLog(device7, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());

                            //方科讯特有报警点位//ICT&FCT
                            //报警记录见Tool类注释
                            List<int> errorNum = new List<int>();
                            try
                            {

                                if (D20 > 0)
                                {
                                    //errorNum = Convert.ToInt32(Math.Log(D20, 2));
                                    CheckErrorList(ref errorNum, ref D20, 1);
                                }
                                if (D21 > 0)
                                {
                                    //errorNum = Convert.ToInt32(Math.Log(D21, 2)) + Convert.ToInt32(Math.Log(32768, 2) + 1);
                                    CheckErrorList(ref errorNum, ref D21, 2);
                                }
                            }
                            catch
                            {

                            }
                            foreach (int item in errorNum)
                            {
                                AddMSG(RichTextBox_WarningBox_7, device7.errorList[item]);
                            }

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device7.DeviceState, device7))
                            {
                                if (!device7.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device7, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device7, data, msg);
                                    device7.AddSendMsgList(transactionID);
                                    if (errorNum.Count >= 0)
                                    {
                                        foreach (int item in errorNum)
                                        {
                                            device7.errorCode.Add(item);
                                            data = SendEvent.ALARM_REPORT(device7, 1, 2, item + 1, device7.errorList[item], out string alarmMsg, out string transactionID_7);
                                            DeviceSendMsg(device7, data, alarmMsg);
                                            Tool.SaveLog(device7, LogMod.运行记录.ToString(), "报警记录==>" + device7.errorList[item]);
                                            device7.AddSendMsgList(transactionID_7);
                                        }
                                    }
                                    device7.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device7.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;

                    }
                }
                else
                {

                }

                // 读取设备的登入登录状态
                if (device7.PLC.ReadCoil("8694").Content == false && logout == false)
                {
                    logout = true;
                    login = false;
                    device7.LoginState = false;
                    string msg;
                    string id;
                    byte[] data = SendEvent.Operator_Login_Logout(device7, "001102", out msg, out id);
                    DeviceSendMsg(device7, data, msg);


                }

                if (device7.PLC.ReadCoil("8694").Content == true && login == false)
                {
                    login = true;
                    logout = false;
                    device7.LoginState = true;
                    string msg;
                    string id;
                    byte[] data = SendEvent.Operator_Login_Logout(device7, "001101", out msg, out id);
                    DeviceSendMsg(device7, data, msg);
                }
                //判断编码格式是否有变更
                if (device7.Sorting != device7.LastTime_Sorting)
                {
                    Sorting = device7.Sorting;
                    NumberSystem = "HEX";
                }
                else
                {
                    Sorting = " ";
                }



                //FCT A面第一次进板
                //第一次读取进板电机运行时间和次数
                if (device7.PLC.ReadCoil("8695").Content == true && FirstRead1 == false)
                {
                    FirstRead1 = true;
                    airCylinder_Count1 = 1;
                    inPCB_Motor1 = device7.PLC.ReadInt16("32").Content;
                }

                //第二次出板的时候电机的运行时间
                if (device7.PLC.ReadCoil("8696").Content == true && SecondRead1 == false)
                {
                    SecondRead1 = true;
                    outPCB_Motor1 = device7.PLC.ReadInt16("34").Content;
                    string msg;
                    string id;
                    byte[] date = SendEvent.UTILITY_DATA_REPORT_ICT(device7, airCylinder_Count1.ToString(), inPCB_Motor1.ToString(), outPCB_Motor1.ToString(), NumberSystem, Sorting, out msg, out id);
                    DeviceSendMsg(device7, date, msg);
                    device7.LastTime_Sorting = device7.Sorting;
                }



                //FCT B面第一次进板
                //第一次读取进板电机运行时间和次数
                if (device7.PLC.ReadCoil("8697").Content == true && FirstRead2 == false)
                {
                    FirstRead2 = true;
                    airCylinder_Count2 = 1;
                    inPCB_Motor2 = device7.PLC.ReadInt16("42").Content;
                }


                //第二次出板的时候电机的运行时间
                if (device7.PLC.ReadCoil("8698").Content == true && SecondRead2 == false)
                {
                    SecondRead2 = true;
                    outPCB_Motor2 = device7.PLC.ReadInt16("44").Content;
                    string msg;
                    string id;
                    byte[] date = SendEvent.UTILITY_DATA_REPORT_ICT(device7, airCylinder_Count2.ToString(), inPCB_Motor2.ToString(), outPCB_Motor2.ToString(), NumberSystem, Sorting, out msg, out id);
                    DeviceSendMsg(device7, date, msg);
                    device7.LastTime_Sorting = device7.Sorting;
                }

                if (device7.PLC.ReadCoil("8695").Content == false) FirstRead1 = false;
                if (device7.PLC.ReadCoil("8696").Content == false) SecondRead1 = false;
                if (device7.PLC.ReadCoil("8697").Content == false) FirstRead2 = false;
                if (device7.PLC.ReadCoil("8698").Content == false) SecondRead2 = false;

                Thread.Sleep(500);
            }
        }

        #endregion

        #region 三是科技
        public void TaskRun2()
        {
            ///上载具
            while (true)
            {
                if (device2.PLCConnect == false)
                {
                    continue;
                }

                int D204 = Convert.ToInt32(device2.PLC.ReadInt16("204").Content);
                int DeviceState = 1;

                switch (D204)
                {
                    case 1:
                        DeviceState = 1;
                        break;
                    case 2:
                        DeviceState = 3;
                        break;
                    case 3:
                        DeviceState = 4;
                        break;
                    case 4:
                        DeviceState = 2;
                        break;
                }



                if (DeviceState != 4)
                {
                    device2.IdleDelay = false;
                    device2.Idle_WaitTime = 0;
                }
                if (DeviceState != device2.DeviceState)
                {
                    if (device2.DeviceState == 2)
                    {
                        foreach (var item in device2.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device2, 2, 2, item, device2.errorList[item - 1], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device2, data, alarmMsg);
                            Tool.SaveLog(device2, LogMod.运行记录.ToString(), "报警消除==>" + device2.errorList[item - 1]);
                            device2.AddSendMsgList(transactionID_1);
                        }
                        device2.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {
                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_2.BackColor = Color.Green;
                                Button_DeviceState_2.Text = "运行中";
                            }));

                            device2.DeviceState = DeviceState;
                            Tool.SaveLog(device2, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device2.DeviceState, device2))
                            {
                                try
                                {
                                    if (!device2.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device2, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device2, data, msg);

                                    device2.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device2.DeviceState);
                                    device2.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device2.IdleDelay == false)
                            {
                                device2.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device2.Idle_WaitTime += 100;
                                        if (device2.Idle_WaitTime >= device2.Idle_Delay_Time)
                                        {
                                            device2.Idle_WaitTime = 0;
                                            device2.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_2.BackColor = Color.Yellow;
                                                Button_DeviceState_2.Text = "待机中";
                                            }));
                                            device2.DeviceState = 2;
                                            Tool.SaveLog(device2, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device2.DeviceState, device2))
                                            {
                                                try
                                                {
                                                    if (!device2.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device2, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device2, data, msg);

                                                    device2.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device2.DeviceState);
                                                    device2.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device2.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_2.BackColor = Color.Orange;
                                Button_DeviceState_2.Text = "停止中";
                            }));

                            device2.DeviceState = DeviceState;
                            Tool.SaveLog(device2, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device2.DeviceState, device2))
                            {
                                try
                                {
                                    if (!device2.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device2, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device2, data, msg);
                                    device2.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device2.DeviceState);
                                    device2.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_2.BackColor = Color.Red;
                                Button_DeviceState_2.Text = "故障中";
                            }));

                            device2.DeviceState = DeviceState;
                            Tool.SaveLog(device2, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());
                            int errorNum = Convert.ToInt32(device2.PLC.ReadInt32("210").Content);
                            if (errorNum > 0)
                            {
                                AddMSG(RichTextBox_WarningBox_2, device2.errorList[errorNum - 1]);
                            }
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device2.DeviceState, device2))
                            {
                                if (!device2.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device2, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device2, data, msg);
                                    device2.AddSendMsgList(transactionID);

                                    if (errorNum > 0)
                                    {
                                        device2.errorCode.Add(errorNum);
                                        data = SendEvent.ALARM_REPORT(device2, 1, 2, errorNum, device2.errorList[errorNum - 1], out string alarmMsg, out string transactionID_2);
                                        DeviceSendMsg(device2, data, alarmMsg);
                                        Tool.SaveLog(device2, LogMod.运行记录.ToString(), "报警记录==>" + device2.errorList[errorNum - 1]);
                                        device2.AddSendMsgList(transactionID_2);
                                    }
                                    device2.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device2.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;

                    }
                }
                else
                {

                }
                Thread.Sleep(500);
            }
        }
        public void TaskRun3()
        {
            ///下盖板
            while (true)
            {
                if (device3.PLCConnect == false)
                {
                    continue;
                }

                int D204 = Convert.ToInt32(device3.PLC.ReadInt16("204").Content);
                int DeviceState = 1;
                switch (D204)
                {
                    case 1:
                        DeviceState = 1;
                        break;
                    case 2:
                        DeviceState = 3;
                        break;
                    case 3:
                        DeviceState = 4;
                        break;
                    case 4:
                        DeviceState = 2;
                        break;
                }

                if (DeviceState != 4)
                {
                    device3.IdleDelay = false;
                    device3.Idle_WaitTime = 0;
                }
                if (DeviceState != device3.DeviceState)
                {
                    if (device3.DeviceState == 2)
                    {
                        foreach (var item in device3.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device3, 2, 2, item, device3.errorList[item - 1], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device3, data, alarmMsg);
                            Tool.SaveLog(device3, LogMod.运行记录.ToString(), "报警消除==>" + device3.errorList[item - 1]);
                            device3.AddSendMsgList(transactionID_1);
                        }
                        device3.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {

                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_3.BackColor = Color.Green;
                                Button_DeviceState_3.Text = "运行中";
                            }));

                            device3.DeviceState = DeviceState;
                            Tool.SaveLog(device3, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device3.DeviceState, device3))
                            {
                                try
                                {
                                    if (!device3.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device3, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device3, data, msg);

                                    device3.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device3.DeviceState);
                                    device3.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device3.IdleDelay == false)
                            {
                                device3.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device3.Idle_WaitTime += 100;
                                        if (device3.Idle_WaitTime >= device3.Idle_Delay_Time)
                                        {
                                            device3.Idle_WaitTime = 0;
                                            device3.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_3.BackColor = Color.Yellow;
                                                Button_DeviceState_3.Text = "待机中";
                                            }));
                                            device3.DeviceState = 2;
                                            Tool.SaveLog(device3, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device3.DeviceState, device3))
                                            {
                                                try
                                                {
                                                    if (!device3.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device3, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device3, data, msg);

                                                    device3.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device3.DeviceState);
                                                    device3.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device3.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_3.BackColor = Color.Orange;
                                Button_DeviceState_3.Text = "停止中";
                            }));

                            device3.DeviceState = DeviceState;
                            Tool.SaveLog(device3, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device3.DeviceState, device3))
                            {
                                try
                                {
                                    if (!device3.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device3, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device3, data, msg);
                                    device3.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device3.DeviceState);
                                    device3.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_3.BackColor = Color.Red;
                                Button_DeviceState_3.Text = "故障中";
                            }));

                            device3.DeviceState = DeviceState;
                            Tool.SaveLog(device3, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());
                            int errorNum = Convert.ToInt32(device3.PLC.ReadInt32("210").Content);
                            if (errorNum > 0)
                            {
                                AddMSG(RichTextBox_WarningBox_3, device3.errorList[errorNum - 1]);
                            }
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device3.DeviceState, device3))
                            {
                                if (!device3.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device3, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device3, data, msg);
                                    device3.AddSendMsgList(transactionID);

                                    if (errorNum > 0)
                                    {
                                        device3.errorCode.Add(errorNum);
                                        data = SendEvent.ALARM_REPORT(device3, 1, 2, errorNum, device3.errorList[errorNum - 1], out string alarmMsg, out string transactionID_3);
                                        DeviceSendMsg(device3, data, alarmMsg);
                                        Tool.SaveLog(device3, LogMod.运行记录.ToString(), "报警记录==>" + device3.errorList[errorNum - 1]);
                                        device3.AddSendMsgList(transactionID_3);
                                    }
                                    device3.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device3.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;

                    }
                }
                else
                {

                }
                Thread.Sleep(500);
            }
        }
        public void TaskRun5()
        {
            ///拆载具
            while (true)
            {
                if (device5.PLCConnect == false)
                {
                    continue;
                }
                int D204 = Convert.ToInt32(device5.PLC.ReadInt16("204").Content);
                int DeviceState = 1;
                switch (D204)
                {
                    case 1:
                        DeviceState = 1;
                        break;
                    case 2:
                        DeviceState = 3;
                        break;
                    case 3:
                        DeviceState = 4;
                        break;
                    case 4:
                        DeviceState = 2;
                        break;
                }

                if (DeviceState != 4)
                {
                    device5.IdleDelay = false;
                    device5.Idle_WaitTime = 0;
                }
                if (DeviceState != device5.DeviceState)
                {
                    if (device5.DeviceState == 2)
                    {
                        foreach (var item in device5.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device5, 2, 2, item, device5.errorList[item - 1], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device5, data, alarmMsg);
                            Tool.SaveLog(device5, LogMod.运行记录.ToString(), "报警消除==>" + device5.errorList[item - 1]);
                            device5.AddSendMsgList(transactionID_1);
                        }
                        device5.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {
                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_5.BackColor = Color.Green;
                                Button_DeviceState_5.Text = "运行中";
                            }));

                            device5.DeviceState = DeviceState;
                            Tool.SaveLog(device5, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device5.DeviceState, device5))
                            {
                                try
                                {
                                    if (!device5.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device5, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device5, data, msg);

                                    device5.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device5.DeviceState);
                                    device5.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device5.IdleDelay == false)
                            {
                                device5.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device5.Idle_WaitTime += 100;
                                        if (device5.Idle_WaitTime >= device5.Idle_Delay_Time)
                                        {
                                            device5.Idle_WaitTime = 0;
                                            device5.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_5.BackColor = Color.Yellow;
                                                Button_DeviceState_5.Text = "待机中";
                                            }));
                                            device5.DeviceState = 2;
                                            Tool.SaveLog(device5, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device5.DeviceState, device5))
                                            {
                                                try
                                                {
                                                    if (!device5.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device5, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device5, data, msg);

                                                    device5.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device5.DeviceState);
                                                    device5.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device5.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_5.BackColor = Color.Orange;
                                Button_DeviceState_5.Text = "停止中";
                            }));

                            device5.DeviceState = DeviceState;
                            Tool.SaveLog(device5, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device5.DeviceState, device5))
                            {
                                try
                                {
                                    if (!device5.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device5, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device5, data, msg);
                                    device5.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device5.DeviceState);
                                    device5.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_5.BackColor = Color.Red;
                                Button_DeviceState_5.Text = "故障中";
                            }));

                            device5.DeviceState = DeviceState;
                            Tool.SaveLog(device5, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());
                            int errorNum = Convert.ToInt32(device5.PLC.ReadInt32("210").Content);
                            if (errorNum > 0)
                            {
                                AddMSG(RichTextBox_WarningBox_5, device5.errorList[errorNum - 1]);
                            }
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device5.DeviceState, device5))
                            {
                                if (!device5.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device5, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device5, data, msg);
                                    device5.AddSendMsgList(transactionID);
                                    if (errorNum > 0)
                                    {
                                        device5.errorCode.Add(errorNum);
                                        data = SendEvent.ALARM_REPORT(device5, 1, 2, errorNum, device5.errorList[errorNum - 1], out string alarmMsg, out string transactionID_5);
                                        DeviceSendMsg(device5, data, alarmMsg);
                                        Tool.SaveLog(device5, LogMod.运行记录.ToString(), "报警记录==>" + device5.errorList[errorNum - 1]);
                                        device5.AddSendMsgList(transactionID_5);
                                    }
                                    device5.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device5.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;

                    }
                }
                else
                {

                }
                Thread.Sleep(500);
            }
        }
        public void TaskRun9()
        {
            //移栽机
            while (true)
            {
                if (device9.PLCConnect == false)
                {
                    continue;
                }
                int D204 = Convert.ToInt32(device9.PLC.ReadInt16("204").Content);
                int DeviceState = 1;
                switch (D204)
                {
                    case 1:
                        DeviceState = 1;
                        break;
                    case 2:
                        DeviceState = 3;
                        break;
                    case 3:
                        DeviceState = 4;
                        break;
                    case 4:
                        DeviceState = 2;
                        break;
                }

                if (DeviceState != 4)
                {
                    device9.IdleDelay = false;
                    device9.Idle_WaitTime = 0;
                }
                if (DeviceState != device9.DeviceState)
                {
                    if (device9.DeviceState == 2)
                    {
                        foreach (var item in device9.errorCode)
                        {
                            byte[] data = SendEvent.ALARM_REPORT(device9, 2, 2, item, device9.errorList[item - 1], out string alarmMsg, out string transactionID_1);
                            DeviceSendMsg(device9, data, alarmMsg);
                            Tool.SaveLog(device9, LogMod.运行记录.ToString(), "报警消除==>" + device9.errorList[item - 1]);
                            device9.AddSendMsgList(transactionID_1);
                        }
                        device9.errorCode.Clear();
                    }
                    switch (DeviceState)
                    {
                        case 1:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_9.BackColor = Color.Green;
                                Button_DeviceState_9.Text = "运行中";
                            }));

                            device9.DeviceState = DeviceState;
                            Tool.SaveLog(device9, LogMod.运行记录.ToString(), DeviceStateEnum.设备开始运行.ToString());

                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device9.DeviceState, device9))
                            {
                                try
                                {
                                    if (!device9.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device9, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device9, data, msg);

                                    device9.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device9.DeviceState);
                                    device9.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }

                            }

                            break;
                        case 3:
                            if (device9.IdleDelay == false)
                            {
                                device9.IdleDelay = true;
                                Task.Run(() =>
                                {
                                    while (true)
                                    {
                                        device9.Idle_WaitTime += 100;
                                        if (device9.Idle_WaitTime >= device9.Idle_Delay_Time)
                                        {
                                            device9.Idle_WaitTime = 0;
                                            device9.IdleDelay = false;
                                            this.BeginInvoke(new Action(() =>
                                            {
                                                Button_DeviceState_9.BackColor = Color.Yellow;
                                                Button_DeviceState_9.Text = "待机中";
                                            }));
                                            device9.DeviceState = 2;
                                            Tool.SaveLog(device9, LogMod.运行记录.ToString(), DeviceStateEnum.设备待机.ToString());
                                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device9.DeviceState, device9))
                                            {
                                                try
                                                {
                                                    if (!device9.TCPConnect)
                                                    {
                                                        return;
                                                    }
                                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device9, DeviceState.ToString(), out string msg, out string transactionID);
                                                    DeviceSendMsg(device9, data, msg);

                                                    device9.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device9.DeviceState);
                                                    device9.AddSendMsgList(transactionID);
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            return;
                                        }
                                        if (device9.IdleDelay == false)
                                        {
                                            return;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }

                            break;
                        case 4:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_9.BackColor = Color.Orange;
                                Button_DeviceState_9.Text = "停止中";
                            }));

                            device9.DeviceState = DeviceState;
                            Tool.SaveLog(device9, LogMod.运行记录.ToString(), DeviceStateEnum.设备停止.ToString());
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device9.DeviceState, device9))
                            {
                                try
                                {
                                    if (!device9.TCPConnect)
                                    {
                                        continue;
                                    }
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device9, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device9, data, msg);
                                    device9.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device9.DeviceState);
                                    device9.AddSendMsgList(transactionID);
                                }
                                catch
                                {

                                }
                            }

                            break;
                        case 2:
                            this.BeginInvoke(new Action(() =>
                            {
                                Button_DeviceState_9.BackColor = Color.Red;
                                Button_DeviceState_9.Text = "故障中";
                            }));

                            device9.DeviceState = DeviceState;
                            Tool.SaveLog(device9, LogMod.运行记录.ToString(), DeviceStateEnum.设备报警.ToString());
                            int errorNum = Convert.ToInt32(device9.PLC.ReadInt32("210").Content);
                            if (errorNum > 0)
                            {
                                AddMSG(RichTextBox_WarningBox_9, device9.errorList[errorNum - 1]);
                            }
                            if (CheckT3(EventList.EQP_STATUS_REPORT.ToString() + device9.DeviceState, device9))
                            {
                                if (!device9.TCPConnect)
                                {
                                    continue;
                                }
                                try
                                {
                                    byte[] data = SendEvent.EQP_STATUS_REPORT(device9, DeviceState.ToString(), out string msg, out string transactionID);
                                    DeviceSendMsg(device9, data, msg);
                                    device9.AddSendMsgList(transactionID);
                                    if (errorNum > 0)
                                    {
                                        device9.errorCode.Add(errorNum);
                                        data = SendEvent.ALARM_REPORT(device9, 1, 2, errorNum, device9.errorList[errorNum - 1], out string alarmMsg, out string transactionID_9);
                                        DeviceSendMsg(device9, data, alarmMsg);
                                        Tool.SaveLog(device9, LogMod.运行记录.ToString(), "报警记录==>" + device9.errorList[errorNum - 1]);
                                        device9.AddSendMsgList(transactionID_9);
                                    }
                                    device9.AddSendEventList(EventList.EQP_STATUS_REPORT.ToString() + device9.DeviceState);
                                }
                                catch
                                {

                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
                else
                {

                }
                Thread.Sleep(500);
            }
        }
        #endregion

        #endregion

        #region 上板机Port状态
        private void SBJPortReport()
        {
            int[] portList = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };//对应1-4 port的当前状态,从角标1开始计
            bool[] stateKeep = { true, false, false, false, false, false, false, false, false };//对应1-8 port的当前状态保持,从角标1开始计
            int scanPass = 0;

            //port1、2、5、6状态为1表示缺料，需要配送，port3、4、7、8状态为1表示出料框满需要卸载
            while (true)
            {
                scanPass += 100;
                if (device1.PLCConnect == false)
                {
                    continue;
                }
                portList[1] = Convert.ToInt32(device1.PLC.ReadInt16("121").Content);
                portList[4] = Convert.ToInt32(device1.PLC.ReadInt16("122").Content);
                portList[2] = (device1.PLC.ReadDiscrete("11").Content == true && device1.PLC.ReadDiscrete("15").Content == false) ? 1 : 0;
                portList[3] = (device1.PLC.ReadDiscrete("10").Content == true && device1.PLC.ReadDiscrete("15").Content == true) ? 1 : 0;

                portList[5] = Convert.ToInt32(device1.PLC.ReadInt16("131").Content);
                portList[8] = Convert.ToInt32(device1.PLC.ReadInt16("132").Content);
                portList[6] = (device1.PLC.ReadDiscrete("21").Content == true && device1.PLC.ReadDiscrete("25").Content == false) ? 1 : 0;
                portList[7] = (device1.PLC.ReadDiscrete("20").Content == true && device1.PLC.ReadDiscrete("15").Content == true) ? 1 : 0;
                this.Invoke(new Action(() =>
                {
                    textBox8.Text = portList[1].ToString();
                    textBox12.Text = portList[4].ToString();
                    textBox13.Text = device1.PLC.ReadDiscrete("11").Content.ToString();
                    textBox14.Text = device1.PLC.ReadDiscrete("10").Content.ToString();
                    textBox16.Text = device1.PLC.ReadDiscrete("15").Content.ToString();


                }));

                switch (portList[1])
                {
                    case 0:
                        stateKeep[1] = false;
                        if (Tool.SBJPortState["1"] != portList[1])
                        {
                            Tool.SBJPortState["1"] = portList[1];

                            if (Tool.SBJ_ScanUsing == false && device1.TCPConnect)
                            {
                                //发送Port1载具到位报告
                                //Port1只有在扫码枪未使用时用感应器到位触发事件
                                AddMSG(RichTextBox_WarningBox_1, "Port1载具到位");
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "1", "2", "", out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                    case 1:
                        if (Tool.SBJPortState["1"] != portList[1])
                        {
                            if (stateKeep[1] == false)
                            {
                                stateKeep[1] = true;
                                Task.Run(() =>
                                {
                                    int keepTime = 0;
                                    while (true)
                                    {
                                        keepTime += 100;
                                        if (keepTime > Tool.stateKeepTime)
                                        {
                                            //达到持续时间
                                            Tool.SBJPortState["1"] = portList[1];
                                            stateKeep[1] = false;
                                            AddMSG(RichTextBox_WarningBox_1, "Port1载具请求");
                                            //发送Port1载具请求报告
                                            //只有在AGV自动模式下才发送
                                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                                            {
                                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "1", "1", "", out string returnMsg, out string transactionID);
                                                DeviceSendMsg(device1, data, returnMsg);
                                                device1.AddSendMsgList(transactionID);
                                            }
                                            break;
                                        }
                                        if (stateKeep[1] == false)
                                        {
                                            break;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }
                        }
                        break;
                }

                switch (portList[2])
                {
                    case 0:
                        stateKeep[2] = false;
                        if (Tool.SBJPortState["2"] != portList[2])
                        {
                            Tool.SBJPortState["2"] = portList[2];

                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_A)
                            {
                                if (Tool.CarrierID_A[item.Key] == 1)
                                {
                                    CarrierID = item.Key;
                                    Tool.CarrierID_A[item.Key]++;
                                    break;
                                }
                            }
                            //发送Port2载具到位报告
                            AddMSG(RichTextBox_WarningBox_1, "Port2载具到位");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "2", "2", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }

                        }
                        break;
                    case 1:
                        if (Tool.SBJPortState["2"] != portList[2])
                        {
                            if (stateKeep[2] == false)
                            {
                                stateKeep[2] = true;
                                Task.Run(() =>
                                {
                                    int keepTime = 0;
                                    while (true)
                                    {
                                        keepTime += 100;
                                        if (keepTime > Tool.stateKeepTime)
                                        {
                                            //达到持续时间
                                            Tool.SBJPortState["2"] = portList[2];
                                            stateKeep[2] = false;
                                            AddMSG(RichTextBox_WarningBox_1, "Port2载具请求");
                                            //发送Port2载具请求报告
                                            //只有在AGV自动模式下才发送
                                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                                            {
                                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "2", "1", "", out string returnMsg, out string transactionID);
                                                DeviceSendMsg(device1, data, returnMsg);
                                                device1.AddSendMsgList(transactionID);
                                            }
                                            break;
                                        }
                                        if (stateKeep[2] == false)
                                        {
                                            break;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }
                        }
                        break;
                }

                switch (portList[3])
                {
                    case 0:
                        if (Tool.SBJPortState["3"] != portList[3])
                        {
                            Tool.SBJPortState["3"] = portList[3];
                            //发送Port3载具卸载完成
                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_A)
                            {
                                if (Tool.CarrierID_A[item.Key] == 3)
                                {
                                    CarrierID = item.Key;
                                    break;
                                }
                            }
                            AddMSG(RichTextBox_WarningBox_1, "Port3卸载完成");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "3", "4", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                    case 1:
                        if (Tool.SBJPortState["3"] != portList[3])
                        {
                            Tool.SBJPortState["3"] = portList[3];
                            //发送Port3载具卸载请求
                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_A)
                            {
                                if (Tool.CarrierID_A[item.Key] == 2)
                                {
                                    CarrierID = item.Key;
                                    Tool.CarrierID_A[item.Key]++;
                                    break;
                                }
                            }
                            AddMSG(RichTextBox_WarningBox_1, "Port3卸载请求");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "3", "3", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                }

                switch (portList[4])
                {
                    case 0:
                        if (Tool.SBJPortState["4"] != portList[4])
                        {
                            Tool.SBJPortState["4"] = portList[4];
                            //发送Port4载具卸载完成
                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_A)
                            {
                                if (Tool.CarrierID_A[item.Key] == 4)
                                {
                                    CarrierID = item.Key;
                                    Tool.CarrierID_A.Remove(item.Key);
                                    break;
                                }
                            }
                            AddMSG(RichTextBox_WarningBox_1, "Port4卸载完成");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "4", "3", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                    case 1:
                        if (Tool.SBJPortState["4"] != portList[4])
                        {
                            Tool.SBJPortState["4"] = portList[4];
                            //发送Port4载具卸载请求
                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_A)
                            {
                                if (Tool.CarrierID_A[item.Key] == 3)
                                {
                                    CarrierID = item.Key;
                                    Tool.CarrierID_A[item.Key]++;
                                    break;
                                }
                            }
                            AddMSG(RichTextBox_WarningBox_1, "Port4卸载请求");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "4", "3", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                }

                if (Tool.SBJPortState["1"] == 1 && Tool.SBJPortState["2"] == 1)//表示A轨道缺料
                {
                    if (Tool.SBJPortState["5"] != 1 || Tool.SBJPortState["6"] != 1)
                    {
                        Tool.AGV_Load_Pos = 1;
                    }
                }
                if (Tool.SBJPortState["3"] == 1 && Tool.SBJPortState["4"] == 1)//表示A轨道卸料
                {
                    if (Tool.SBJPortState["7"] != 1 || Tool.SBJPortState["8"] != 1)
                    {
                        Tool.AGV_UnLoad_Pos = 1;
                    }
                }

                switch (portList[5])
                {
                    case 0:
                        stateKeep[5] = false;
                        if (Tool.SBJPortState["5"] != portList[5])
                        {
                            Tool.SBJPortState["5"] = portList[5];

                            if (Tool.SBJ_ScanUsing == false && device1.TCPConnect)
                            {
                                //发送Port5载具到位报告
                                //Port5只有在扫码枪未使用时用感应器到位触发事件
                                AddMSG(RichTextBox_WarningBox_1, "Port5载具到位");
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "5", "2", "", out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                    case 1:
                        if (Tool.SBJPortState["5"] != portList[5])
                        {
                            if (stateKeep[5] == false)
                            {
                                stateKeep[5] = true;
                                Task.Run(() =>
                                {
                                    int keepTime = 0;
                                    while (true)
                                    {
                                        keepTime += 100;
                                        if (keepTime > Tool.stateKeepTime)
                                        {
                                            //达到持续时间
                                            Tool.SBJPortState["5"] = portList[5];
                                            stateKeep[5] = false;
                                            AddMSG(RichTextBox_WarningBox_1, "Port5载具请求");
                                            //发送Port1载具请求报告
                                            //只有在AGV自动模式下才发送
                                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                                            {
                                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "5", "1", "", out string returnMsg, out string transactionID);
                                                DeviceSendMsg(device1, data, returnMsg);
                                                device1.AddSendMsgList(transactionID);
                                            }
                                            break;
                                        }
                                        if (stateKeep[5] == false)
                                        {
                                            break;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }
                        }
                        break;
                }

                switch (portList[6])
                {
                    case 0:
                        stateKeep[6] = false;
                        if (Tool.SBJPortState["6"] != portList[6])
                        {
                            Tool.SBJPortState["6"] = portList[6];

                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_B)
                            {
                                if (Tool.CarrierID_B[item.Key] == 1)
                                {
                                    CarrierID = item.Key;
                                    Tool.CarrierID_B[item.Key]++;
                                    break;
                                }
                            }
                            //发送Port6载具到位报告
                            AddMSG(RichTextBox_WarningBox_1, "Port6载具到位");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "6", "2", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }

                        }
                        break;
                    case 1:
                        if (Tool.SBJPortState["6"] != portList[6])
                        {
                            if (stateKeep[6] == false)
                            {
                                stateKeep[6] = true;
                                Task.Run(() =>
                                {
                                    int keepTime = 0;
                                    while (true)
                                    {
                                        keepTime += 100;
                                        if (keepTime > Tool.stateKeepTime)
                                        {
                                            //达到持续时间
                                            Tool.SBJPortState["6"] = portList[6];
                                            stateKeep[6] = false;
                                            AddMSG(RichTextBox_WarningBox_1, "Port6载具请求");
                                            //发送Port6载具请求报告
                                            //只有在AGV自动模式下才发送
                                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                                            {
                                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "6", "1", "", out string returnMsg, out string transactionID);
                                                DeviceSendMsg(device1, data, returnMsg);
                                                device1.AddSendMsgList(transactionID);
                                            }
                                            break;
                                        }
                                        if (stateKeep[6] == false)
                                        {
                                            break;
                                        }
                                        Thread.Sleep(100);
                                    }
                                });
                            }
                        }
                        break;
                }

                switch (portList[7])
                {
                    case 0:
                        if (Tool.SBJPortState["7"] != portList[7])
                        {
                            Tool.SBJPortState["7"] = portList[7];
                            //发送Port7载具卸载完成
                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_B)
                            {
                                if (Tool.CarrierID_B[item.Key] == 3)
                                {
                                    CarrierID = item.Key;
                                    break;
                                }
                            }
                            AddMSG(RichTextBox_WarningBox_1, "Port7卸载完成");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "7", "4", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                    case 1:
                        if (Tool.SBJPortState["7"] != portList[7])
                        {
                            Tool.SBJPortState["7"] = portList[7];
                            //发送Port7载具卸载请求
                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_B)
                            {
                                if (Tool.CarrierID_B[item.Key] == 2)
                                {
                                    CarrierID = item.Key;
                                    Tool.CarrierID_B[item.Key]++;
                                    break;
                                }
                            }
                            AddMSG(RichTextBox_WarningBox_1, "Port7卸载请求");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "7", "3", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                }

                switch (portList[8])
                {
                    case 0:
                        if (Tool.SBJPortState["8"] != portList[8])
                        {
                            Tool.SBJPortState["8"] = portList[8];
                            //发送Port8载具卸载完成
                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_B)
                            {
                                if (Tool.CarrierID_B[item.Key] == 4)
                                {
                                    CarrierID = item.Key;
                                    Tool.CarrierID_B.Remove(item.Key);
                                    break;
                                }
                            }
                            AddMSG(RichTextBox_WarningBox_1, "Port8卸载完成");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "8", "3", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                    case 1:
                        if (Tool.SBJPortState["8"] != portList[8])
                        {
                            Tool.SBJPortState["8"] = portList[8];
                            //发送Port4载具卸载请求
                            string CarrierID = "";
                            foreach (var item in Tool.CarrierID_B)
                            {
                                if (Tool.CarrierID_B[item.Key] == 3)
                                {
                                    CarrierID = item.Key;
                                    Tool.CarrierID_B[item.Key]++;
                                    break;
                                }
                            }
                            AddMSG(RichTextBox_WarningBox_1, "Port8卸载请求");
                            if (Tool.SBJmode == 1 && device1.TCPConnect)
                            {
                                byte[] data = SendEvent.PORT_STATUS_REPORT(device1, "8  ", "3", CarrierID, out string returnMsg, out string transactionID);
                                DeviceSendMsg(device1, data, returnMsg);
                                device1.AddSendMsgList(transactionID);
                            }
                        }
                        break;
                }

                if (Tool.SBJPortState["5"] == 1 && Tool.SBJPortState["6"] == 1)//表示B轨道缺料
                {
                    if (Tool.SBJPortState["1"] != 1 || Tool.SBJPortState["2"] != 1)
                    {
                        Tool.AGV_Load_Pos = 2;
                    }
                }
                if (Tool.SBJPortState["7"] == 1 && Tool.SBJPortState["8"] == 1)//表示A轨道卸料
                {
                    if (Tool.SBJPortState["3"] != 1 || Tool.SBJPortState["4"] != 1)
                    {
                        Tool.AGV_UnLoad_Pos = 2;
                    }
                }






                if (scanPass > 2000)
                {
                    scanPass = 0;
                    if (Tool.SBJ_ScanUsing == false)
                    {
                        device1.PLC.WriteCoil("8302", true);//扫码枪停用时，每2s写一次扫码OK；
                        device1.PLC.WriteCoil("8303", true);
                    }
                }
                Thread.Sleep(100);


            }

        }

        #endregion

        #region ICT,FCT扫码枪到位感应
        private void ICT_Task()
        {
            bool trigger1 = false;

            bool trigger3 = false;

            while (true)
            {
                if (device6.PLC.ReadDiscrete("22").Content != true && trigger3 == false) //天板不在顶点
                {
                    trigger3 = true;
                    Tool.ICT_FixetureTime.Restart();
                }
                if (device6.PLC.ReadDiscrete("22").Content == true && trigger3 == true)
                {
                    trigger3 = false;
                    Tool.ICT_FixetureTime.Stop();
                }

                if (device6.PLC.ReadDiscrete("10").Content == true && device6.PLC.ReadDiscrete("12").Content == false)//触发进板扫码
                {
                    if (trigger1 == false)
                    {
                        Tool.ICT_StarTime = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));
                        trigger1 = true;
                        Task.Run(() =>
                        {
                            scanDevice6_1.TCPClient.ClientSendMSG("run\r");
                            Thread.Sleep(3000);
                            scanDevice6_1.TCPClient.ClientSendMSG("stop\r");
                        });
                    }
                }
                else
                {
                    trigger1 = false;
                }



                Thread.Sleep(100);
            }
        }

        private void FCT_Task()
        {
            bool trigger1 = false;
            bool trigger2 = false;
            bool trigger3 = false;
            bool trigger4 = false;
            bool trigger5 = false;
            while (true)
            {
                if (device6.PLC.ReadInt16("4").Content == 8)//FCT A轨进板
                {
                    if (trigger4 == false)
                    {
                        trigger4 = true;
                        Tool.FCT_ID1 = scanDevice6_2.ScanMSG;
                        Tool.FCT_StarTime1 = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));
                        if (device7.TCPConnect)
                        {
                            byte[] data = SendEvent.JOB_MOVE_IN_REQUEST(device7, Tool.FCT_ID1, "", out string Msg, out string transactionID);
                            DeviceSendMsg(device7, data, Msg);
                            device7.AddSendMsgList(transactionID);
                        }
                    }
                }
                else
                {
                    if (trigger4 == true)
                    {
                        trigger4 = false;
                    }
                }
                if (device6.PLC.ReadInt16("4").Content == 11)//FCT B轨进板
                {
                    if (trigger5 == false)
                    {
                        trigger5 = true;
                        Tool.FCT_ID2 = scanDevice6_2.ScanMSG;
                        Tool.FCT_StarTime2 = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));
                        if (device7.TCPConnect)
                        {
                            byte[] data = SendEvent.JOB_MOVE_IN_REQUEST(device7, Tool.FCT_ID2, "", out string Msg, out string transactionID);
                            DeviceSendMsg(device7, data, Msg);
                            device7.AddSendMsgList(transactionID);
                        }
                    }
                }
                else
                {
                    if (trigger5 == true)
                    {
                        trigger5 = false;
                    }
                }


                if (device7.PLC.ReadDiscrete("22").Content != true && trigger1 == false) //天板A不在顶点
                {
                    trigger1 = true;
                    Tool.FCT_FixetureTime1.Restart();
                }
                if (device7.PLC.ReadDiscrete("22").Content == true && trigger1 == true)
                {
                    trigger1 = false;
                    Tool.FCT_FixetureTime1.Stop();
                }

                if (device7.PLC.ReadDiscrete("24").Content != true && trigger2 == false) //天板B不在顶点
                {
                    trigger2 = true;
                    Tool.FCT_FixetureTime2.Restart();
                }
                if (device7.PLC.ReadDiscrete("24").Content == true && trigger2 == true)
                {
                    trigger2 = false;
                    Tool.FCT_FixetureTime2.Stop();
                }

                if (device7.PLC.ReadDiscrete("10").Content == true)
                {
                    Tool.FCT_PartInTime1 = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));
                }
                if (device7.PLC.ReadDiscrete("16").Content == true)
                {
                    Tool.FCT_PartInTime2 = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));
                }


                if (device6.PLC.ReadInt16("1000").Content == 11)//触发出板扫码
                {
                    if (trigger3 == false)
                    {
                        trigger3 = true;
                        Task.Run(() =>
                        {
                            scanDevice6_2.TCPClient.ClientSendMSG("run\r");
                            Thread.Sleep(3000);
                            scanDevice6_2.TCPClient.ClientSendMSG("stop\r");
                        });
                    }
                }
                else
                {
                    trigger3 = false;
                }

                Thread.Sleep(100);
            }
        }


        #endregion


        private void Task_BlueLight()
        {
            string msg = "";
            string id = msg;
            byte[] data1 = null;
            byte[] data2 = null;
            List<string> waringinfo =new List<string>();
            OperateResult result = new OperateResult();
            this.BeginInvoke((Action<RichTextBox>)(theRichBox => { theRichBox.AppendText("通信检测线程已经启动\r\n"); }), richTextBox1);
            while (true)
            {
                waringinfo.Clear();
                // 上板机
                if (device1.TCPConnect == true)
                {
                  result =  device1.PLC.Write("125", (short)1);
                }
                if(device1.TCPConnect = false || result.IsSuccess==false)
                {
                    waringinfo.Add("上板机网络断开");
                }


                //上载具
                if (device2.TCPConnect == true)
                {
                  result = device2.PLC.Write("230", (short)1);
                }
                if (device2.TCPConnect = false || result.IsSuccess == false)
                {
                    waringinfo.Add("上载具网络断开");
                }


                //下盖板
                if (device3.TCPConnect == true)
                {
                    result = device3.PLC.Write("230", (short)1);
                }

                if (device3.TCPConnect = false || result.IsSuccess == false)
                {
                    waringinfo.Add("上载具网络断开");
                }


                //暂存机
                if (device4.TCPConnect == true)
                {
                    result = device4.PLC.Write("125", (short)1);
                }
                if (device4.TCPConnect = false || result.IsSuccess == false)
                {
                    waringinfo.Add("暂存机网络断开");
                }



                //拆载具
                if (device5.TCPConnect == true)
                {
                    result = device5.PLC.Write("230", (short)1);
                }

                if(device5.TCPConnect = false || result.IsSuccess == false)
                {
                    waringinfo.Add("拆载具网络断开");
                }


                //ICT
                if (device6.TCPConnect == true)
                {
                    result = device6.PLC.Write("1002", (short)22);
                }
                else
                {
                    result = device6.PLC.Write("1002", (short)11);
                    waringinfo.Add("ICT网络断开");
                }
                if (device6.TCPConnect = false || result.IsSuccess == false)
                {
                    waringinfo.Add("拆载具网络断开");
                }


                //FCT
                if (device7.TCPConnect == true)
                {
                    result = device7.PLC.Write("1002", (short)22);
                }
                else
                {
                    device7.PLC.Write("1002", (short)11);
                    waringinfo.Add("FCT网络断开");
                }
                if (device7.TCPConnect = false || result.IsSuccess == false)
                {
                    waringinfo.Add("拆载具网络断开");
                }

                //翻板机
                if (device8.TCPConnect==true)
                {
                    result = device8.PLC.Write("125", (short)1);
                }
                if (device8.TCPConnect = false || result.IsSuccess == false)
                {
                    waringinfo.Add("翻板机网络断开");
                }


                //移栽机
                if(device9.TCPConnect==true)
                {
                    result = device9.PLC.Write("230", (short)1);
                }
                if (device9.TCPConnect = false || result.IsSuccess == false)
                {
                    waringinfo.Add("移栽机网络断开");
                }



                if(waringinfo.Count>0 && form2.Visible==false)
                {
                    this.Invoke((Action<Form2>)(theForm => { theForm.Show(); }), form2);
                    for(int i=0;i<waringinfo.Count;i++)
                    {
                       
                        this.Invoke((Action<Form2>)(theForm => { theForm.richTextBox1.AppendText(DateTime.Now.ToString() + ":" + waringinfo[i] + "\r\n"); }), form2);
                    }
                }
                if(waringinfo.Count>0 && form2.Visible ==true)
                {
                    
                    this.Invoke((Action<Form2>)(theForm => { theForm.richTextBox1.Clear(); }), form2);
                    for (int i = 0; i < waringinfo.Count; i++)
                    {
                        this.Invoke((Action<Form2>)(theForm => { theForm.richTextBox1.AppendText(DateTime.Now.ToString() + ":" + waringinfo[i] + "\r\n"); }), form2);
                    }
                }
                if (waringinfo.Count == 0 && form2.Visible == true)
                {
                    this.Invoke((Action<Form2>)(theForm => { theForm.Hide(); }), form2);
                }

                Thread.Sleep(3000);
            }
        }

        #endregion

        #region  Form事件///////// Form事件///////// Form事件///////// Form事件///////// Form事件///////// Form事件///////// Form事件///////// Form事件///////// Form事件/////////
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //this.Close();
            System.Environment.Exit(0);

        }
        private void Button_Scan_1_1_Click(object sender, EventArgs e)
        {
            ChangeButtonState("Button_Scan_1_1");
        }

        private void Button_Scan_1_2_Click(object sender, EventArgs e)
        {
            ChangeButtonState("Button_Scan_1_2");
        }
        private void Button_Scan_6_1_Click(object sender, EventArgs e)
        {
            ChangeButtonState("Button_Scan_6_1");
        }
        private void Button_Scan_6_2_Click(object sender, EventArgs e)
        {
            ChangeButtonState("Button_Scan_6_2");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                textBox2.Text = deviceList[Convert.ToInt32(textBox3.Text)].PLC.ReadInt16(textBox1.Text).Content.ToString();
            }
            catch
            {

            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                deviceList[Convert.ToInt32(textBox3.Text)].PLC.Write(textBox1.Text, Convert.ToInt16(textBox2.Text));
            }
            catch
            {

            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                textBox2.Text = deviceList[Convert.ToInt32(textBox3.Text)].PLC.ReadCoil(textBox1.Text).Content.ToString();
            }
            catch
            {

            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                deviceList[Convert.ToInt32(textBox3.Text)].PLC.WriteCoil(textBox1.Text, Convert.ToBoolean(textBox2.Text));
            }
            catch
            {

            }
            //try
            //{
            //    device1.PLC.WriteCoil(textBox1.Text, Convert.ToBoolean(textBox2.Text));
            //}
            //catch
            //{

            //}
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //设备1保存参数
            BoundConfig(1);

            //扫码枪参数
            try
            {
                scanDevice1_1.TCP_IP = textBox5.Text;
                scanDevice1_1.TCP_Port = Convert.ToInt32(textBox4.Text);
                scanDevice1_1.WriteConfig();
                scanDevice1_2.TCP_IP = textBox7.Text;
                scanDevice1_2.TCP_Port = Convert.ToInt32(textBox6.Text);
                scanDevice1_2.WriteConfig();
            }
            catch
            {
                MessageBox.Show("扫码枪参数有误");
            }

            //上板机独用
            try
            {
                Tool.SBJ_inputWaiteTime = Convert.ToInt32(TextBox_InputWaiteTime_1.Text);
                Tool.WriteConfig();
            }
            catch
            {
                MessageBox.Show("参数有误");
            }


        }
        private void button10_Click(object sender, EventArgs e)
        {
            //设备2保存参数
            BoundConfig(2);
        }
        private void button17_Click(object sender, EventArgs e)
        {
            //设备3保存参数
            BoundConfig(3);
        }
        private void button26_Click(object sender, EventArgs e)
        {
            //设备4保存参数
            BoundConfig(4);
        }
        private void button34_Click(object sender, EventArgs e)
        {
            //设备5保存参数
            BoundConfig(5);
        }
        private void button39_Click(object sender, EventArgs e)
        {
            //设备6保存参数
            BoundConfig(6);

            //扫码枪参数
            try
            {
                scanDevice6_1.TCP_IP = textBox20.Text;
                scanDevice6_1.TCP_Port = Convert.ToInt32(textBox19.Text);
                scanDevice6_1.WriteConfig();
                scanDevice6_2.TCP_IP = textBox18.Text;
                scanDevice6_2.TCP_Port = Convert.ToInt32(textBox17.Text);
                scanDevice6_2.WriteConfig();
                Tool.WriteConfig();
            }
            catch
            {
                MessageBox.Show("扫码枪参数有误");
            }
        }
        private void button44_Click(object sender, EventArgs e)
        {
            //设备7保存参数
            BoundConfig(7);
            Tool.WriteConfig();
        }
        private void button49_Click(object sender, EventArgs e)
        {
            //设备8保存参数
            BoundConfig(8);
        }
        private void button54_Click(object sender, EventArgs e)
        {
            //设备9保存参数
            BoundConfig(9);
        }

        #region 通讯状态/重连
        private void Button_PLCReconnect_1_Click(object sender, EventArgs e)
        {
            ChangeButtonState(1, "PLC_Reconnect");

        }
        private void Button_PLCReconnect_2_Click(object sender, EventArgs e)
        {
            ChangeButtonState(2, "PLC_Reconnect");

        }
        private void Button_PLCReconnect_3_Click(object sender, EventArgs e)
        {
            ChangeButtonState(3, "PLC_Reconnect");

        }

        private void Button_PLCReconnect_4_Click(object sender, EventArgs e)
        {
            ChangeButtonState(4, "PLC_Reconnect");

        }

        private void Button_PLCReconnect_5_Click(object sender, EventArgs e)
        {
            ChangeButtonState(5, "PLC_Reconnect");

        }

        private void Button_PLCReconnect_6_Click(object sender, EventArgs e)
        {
            ChangeButtonState(6, "PLC_Reconnect");

        }

        private void Button_PLCReconnect_7_Click(object sender, EventArgs e)
        {
            ChangeButtonState(7, "PLC_Reconnect");

        }

        private void Button_PLCReconnect_8_Click(object sender, EventArgs e)
        {
            ChangeButtonState(8, "PLC_Reconnect");

        }
        private void Button_PLCReconnect_9_Click(object sender, EventArgs e)
        {
            ChangeButtonState(9, "PLC_Reconnect");

        }

        private void Button_TCPReconnect_1_Click(object sender, EventArgs e)
        {
            ChangeButtonState(1, "TCP_Reconnect");
        }

        private void Button_TCPReconnect_2_Click(object sender, EventArgs e)
        {
            ChangeButtonState(2, "TCP_Reconnect");
        }

        private void Button_TCPReconnect_3_Click(object sender, EventArgs e)
        {
            ChangeButtonState(3, "TCP_Reconnect");
        }

        private void Button_TCPReconnect_4_Click(object sender, EventArgs e)
        {
            ChangeButtonState(4, "TCP_Reconnect");
        }

        private void Button_TCPReconnect_5_Click(object sender, EventArgs e)
        {
            ChangeButtonState(5, "TCP_Reconnect");
        }

        private void Button_TCPReconnect_6_Click(object sender, EventArgs e)
        {
            ChangeButtonState(6, "TCP_Reconnect");
        }

        private void Button_TCPReconnect_7_Click(object sender, EventArgs e)
        {
            ChangeButtonState(7, "TCP_Reconnect");
        }

        private void Button_TCPReconnect_8_Click(object sender, EventArgs e)
        {
            ChangeButtonState(8, "TCP_Reconnect");
        }

        private void Button_TCPReconnect_9_Click(object sender, EventArgs e)
        {
            ChangeButtonState(9, "TCP_Reconnect");
        }

        private void Button_PLCConnect_1_Click(object sender, EventArgs e)
        {
            ChangeButtonState(1, "PLC_Connect");
        }
        private void Button_PLCConnect_2_Click(object sender, EventArgs e)
        {
            ChangeButtonState(2, "PLC_Connect");
        }

        private void Button_PLCConnect_3_Click(object sender, EventArgs e)
        {
            ChangeButtonState(3, "PLC_Connect");
        }

        private void Button_PLCConnect_4_Click(object sender, EventArgs e)
        {
            ChangeButtonState(4, "PLC_Connect");
        }

        private void Button_PLCConnect_5_Click(object sender, EventArgs e)
        {
            ChangeButtonState(5, "PLC_Connect");
        }

        private void Button_PLCConnect_6_Click(object sender, EventArgs e)
        {
            ChangeButtonState(6, "PLC_Connect");
        }

        private void Button_PLCConnect_7_Click(object sender, EventArgs e)
        {
            ChangeButtonState(7, "PLC_Connect");
        }

        private void Button_PLCConnect_8_Click(object sender, EventArgs e)
        {
            ChangeButtonState(8, "PLC_Connect");
        }

        private void Button_PLCConnect_9_Click(object sender, EventArgs e)
        {
            ChangeButtonState(9, "PLC_Connect");
        }

        private void Button_TCPConnect_1_Click(object sender, EventArgs e)
        {
            ChangeButtonState(1, "TCP_Connect");
        }

        private void Button_TCPConnect_2_Click(object sender, EventArgs e)
        {
            ChangeButtonState(2, "TCP_Connect");
        }

        private void Button_TCPConnect_3_Click(object sender, EventArgs e)
        {
            ChangeButtonState(3, "TCP_Connect");
        }

        private void Button_TCPConnect_4_Click(object sender, EventArgs e)
        {
            ChangeButtonState(4, "TCP_Connect");
        }

        private void Button_TCPConnect_5_Click(object sender, EventArgs e)
        {
            ChangeButtonState(5, "TCP_Connect");
        }

        private void Button_TCPConnect_6_Click(object sender, EventArgs e)
        {
            ChangeButtonState(6, "TCP_Connect");
        }

        private void Button_TCPConnect_7_Click(object sender, EventArgs e)
        {
            ChangeButtonState(7, "TCP_Connect");
        }

        private void Button_TCPConnect_8_Click(object sender, EventArgs e)
        {
            ChangeButtonState(8, "TCP_Connect");
        }

        private void Button_TCPConnect_9_Click(object sender, EventArgs e)
        {
            ChangeButtonState(9, "TCP_Connect");
        }
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            MyControlAutosize.controlAutoSize(this);
        }






        #endregion

        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            GC.Collect();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex != -1)
            {
                try
                {
                    double bankuan = Convert.ToDouble(OpearationTxt.ReadIni("Product", "bankuan", "D:\\EQP\\PartList\\" + comboBox1.Text + ".ini"));
                    textBox9.Text = bankuan.ToString();
                }
                catch
                {

                }
            }
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            byte[] data = SendEvent.RECIPE_MODIFY_REPORT(device1, ModifyFlag.Modify.ToString(), out string alarmMsg, out string transactionID_1);
            DeviceSendMsg(device1, data, alarmMsg);
        }

        private void button11_Click(object sender, EventArgs e)
        {
            byte[] data = SendEvent.JOB_MOVE_IN_REQUEST(device1, "TestJobID", "TestJobType", out string alarmMsg, out string transactionID_1);
            DeviceSendMsg(device1, data, alarmMsg);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            //string b = File.ReadAllText("C:\\Users\\11427\\Desktop\\321.txt");
            //List<string> bb = b.Split(',').ToList();
            //try
            //{
            //    byte[] data = SendEvent.ICT_JOB_SEND_REPORT(device1, bb, "testID", "testJudge", out string alarmMsg, out string transactionID_1);
            //    DeviceSendMsg(device1, data, alarmMsg);
            //}
            //catch
            //{

            //}

            Tool.ICT_StopTime = Convert.ToDouble(DateTime.Now.ToString("yyyyMMddHHmmss"));
            Tool.ICT_StarTime = Tool.ICT_StopTime - 20;
            string info = File.ReadAllText("C:\\Users\\11427\\Desktop\\321.txt");
            int processTime;
            if (Tool.ICT_StopTime - Tool.ICT_StarTime > Int32.MaxValue)
            {
                processTime = 0;
            }
            else
            {
                processTime = Convert.ToInt32(Tool.ICT_StopTime - Tool.ICT_StarTime);
            }
            int fixtureTime = Convert.ToInt32(Tool.ICT_FixetureTime.ElapsedMilliseconds / 1000);

            fixtureTime = 13;
            scanDevice6_1.ScanMSG = "532678412A";
            EDC_REPORT ICT_EDC_REPORT = Tool.CheckEDCReport_ICT(info, scanDevice6_1.ScanMSG, processTime, fixtureTime, out List<string> testData,out device6.Sorting);

            if (ICT_EDC_REPORT.result == true)//表解析成功
            {
                Tool.ICT_EDC_REPORT = ICT_EDC_REPORT;
                byte[] data = SendEvent.ICT_JOB_SEND_REPORT(device6, testData, ICT_EDC_REPORT.JobID, ICT_EDC_REPORT.Pass.ToString(), out string Msg, out string transactionID);
                DeviceSendMsg(device6, data, Msg);
                device6.AddSendMsgList(transactionID);

                data = SendEvent.EDC_REPORT(device6, ICT_EDC_REPORT, processTime.ToString(), Tool.ICT_StarTime.ToString(), Tool.ICT_StopTime.ToString(), out Msg, out transactionID);
                DeviceSendMsg(device6, data, Msg);
                device6.AddSendMsgList(transactionID);

            }
        }

        private void button16_Click(object sender, EventArgs e)
        {

        }

        private void button16_Click_1(object sender, EventArgs e)
        {
            try
            {
                textBox2.Text = deviceList[Convert.ToInt32(textBox3.Text)].PLC.ReadDiscrete(textBox1.Text).Content.ToString();
            }
            catch
            {

            }
        }

        private void button20_Click(object sender, EventArgs e)
        {

        }

        private void Button_ScanUsing_1_Click(object sender, EventArgs e)
        {
            ChangeButtonState("Button_ScanUsing_1");
            Tool.WriteConfig();
        }

        private void Button_Mode_1_Click(object sender, EventArgs e)
        {
            ChangeButtonState("Button_Mode_1");
        }

        private void button21_Click(object sender, EventArgs e)
        {

        }

        private void Button_ScanUsing_6_Click(object sender, EventArgs e)
        {
            ChangeButtonState("Button_ScanUsing_6");
            Tool.WriteConfig();
        }

        private void Button_ScanUsing_7_Click(object sender, EventArgs e)
        {
            ChangeButtonState("Button_ScanUsing_7");
            Tool.WriteConfig();
        }

        private void button12_Click(object sender, EventArgs e)
        {
            string msg = "";
            string ID = "";
            if (device1.TCPConnect == true && device2.TCPConnect == true && device3.TCPConnect == true && device4.TCPConnect == true && device5.TCPConnect == true && device6.TCPConnect == true && device7.TCPConnect == true && device8.TCPConnect == true && device9.TCPConnect == true)
            {
                if (AutoMode == false)
                {
                    if (device1.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device1, "1", out msg, out ID);
                        DeviceSendMsg(device1, sendmsg, msg);
                    }

                    if (device2.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device2, "1", out msg, out ID);
                        DeviceSendMsg(device2, sendmsg, msg);
                    }
                    if (device3.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device3, "1", out msg, out ID);
                        DeviceSendMsg(device3, sendmsg, msg);
                    }
                    if (device4.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device4, "1", out msg, out ID);
                        DeviceSendMsg(device4, sendmsg, msg);
                    }
                    if (device5.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device5, "1", out msg, out ID);
                        DeviceSendMsg(device5, sendmsg, msg);
                    }

                    if (device6.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device6, "1", out msg, out ID);
                        DeviceSendMsg(device6, sendmsg, msg);
                    }
                    if (device7.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device7, "1", out msg, out ID);
                        DeviceSendMsg(device7, sendmsg, msg);
                    }
                    if (device8.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device8, "1", out msg, out ID);
                        DeviceSendMsg(device8, sendmsg, msg);
                    }
                    if (device9.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device9, "1", out msg, out ID);
                        DeviceSendMsg(device9, sendmsg, msg);
                    }
                    AutoMode = true;
                    button12.BackColor = Color.Green;
                    button12.Text = "CIM - Auto";
                }
                else
                {
                    if (device1.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device1, "0", out msg, out ID);
                        DeviceSendMsg(device1, sendmsg, msg);
                    }

                    if (device2.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device2, "0", out msg, out ID);
                        DeviceSendMsg(device2, sendmsg, msg);
                    }
                    if (device3.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device3, "0", out msg, out ID);
                        DeviceSendMsg(device3, sendmsg, msg);
                    }
                    if (device4.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device4, "0", out msg, out ID);
                        DeviceSendMsg(device4, sendmsg, msg);
                    }
                    if (device5.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device5, "0", out msg, out ID);
                        DeviceSendMsg(device5, sendmsg, msg);
                    }

                    if (device6.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device6, "0", out msg, out ID);
                        DeviceSendMsg(device6, sendmsg, msg);
                    }
                    if (device7.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device7, "0", out msg, out ID);
                        DeviceSendMsg(device7, sendmsg, msg);
                    }
                    if (device8.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device8, "0", out msg, out ID);
                        DeviceSendMsg(device8, sendmsg, msg);
                    }
                    if (device9.TCPConnect == true)
                    {
                        byte[] sendmsg = SendEvent.CIM_CONTROL_MODE_COMMAND(device9, "0", out msg, out ID);
                        DeviceSendMsg(device9, sendmsg, msg);
                    }
                    AutoMode = false;
                    button12.BackColor = Color.Yellow;
                    button12.Text = "CIM - Manual";
                }

            }
        }
    }

    public enum DeviceStateEnum
    {
        设备开始运行,
        设备待机,
        设备停止,
        设备报警
    }
    public enum LogMod
    {
        运行记录,
        Mes交互记录,
    }

    public enum EventList
    {
        EQP_STATUS_REPORT,
        ALARM_REPORT
    }
    public enum ModifyFlag//配方上报专用
    {
        Create,
        Modify,
        Delete
    }

}
